public class Example01:
public void static main(String[] args){
HashSet set = new HashSet();
set.add("peter");
set.add("morton");
set.add("mary");
set.add("mary);
Iterator it = set.iterator();
while(it.hashNext()){
Object o = it.next();
}
}
}
public class Example03{
public void static main(String[] args){
HashSet set = new HashSet();
set.add(new Person("22","Mike");
set.add(new Person("22","Mike");
}
}
//重写toString()方法
public String toString(){
return id + ":" + name;
}
//重写compareTo()
public int compareTo(Object o){
Person p = (Person) o;
x = Integer.parseInt(this.id);
y = Integer.parseInt(p.id);
if((x - y ) > 0){
return 1;
}
if(x == y ){
return p.name.compareTo(this.name);
}
return -1;
}
}
class Example05{
public void static main(Stringp[] args){
TreeSet set = new TreeSet();
set.add(new Person("33","sldf");
...
set.add(new Person("34","sfgg");
}
}
还可以自己实现comparator写个自定义的比较器
class MyComparator implements comparator{
//重写compare()方法
public int compare(Object o1, Object o2){
//强转为String
String s1 = (String) o1;
String s2 = (String) o2;
return (s1.length - s2.length);
}
}
public class Example06{
public void static main(String[] args){
//实例化TreeMap,并且传入自定义的比较器
TreeMap tm = new TreeMap(new MyComparator);
tm.add("sssssssssssss");
tm.add("adfsdfa");
tm.add("trwtwrt");
//添加迭代器
Iterator it = tm.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
public class Example16{
public void static main(String[] args){
Map map = new Map();
map.put("1","aaa"); //储存键值对,注意Collection是add(),Map是Put()
map.put("2","bbb");
map.put("3","ccc");
map.put("4","ddd");
Set key = map.keySet();
Iterator it = key.iterator();
while(it.hasNext()){
String s = it.next();
String ss = map.get(s);
}
}
}
第二种遍历方法:
public class Example17{
public void static main(String[] args){
Map map = new Map();
map.put("1","aaa"); //储存键值对,注意Collection是add(),Map是Put()
map.put("2","bbb");
map.put("3","ccc");
map.put("4","ddd");
Set set = map.entrySet();
Iterator it = set.Iterator();
while(it.hasNext()){
Map.Entry me = it.next();
Object key = me.getKey();
Object value = me.getValue();
}
}
}
public class Example18 {
public void static main(String[] args){
Map map = new LinkedHashMap();
map.put("1","qqq");
map.put("2","www");
map.put("3","eee");
//获取全部键的集合
Set keys = map.keySet();
//获取迭代器
Iterator it = keys.iterator();
while(it.hasNext()){
Object key = it.next();
Object value = map.get(key);
System.out.println(value);
}
}
}