本帖最后由 梦里花-静 于 2014-4-6 16:04 编辑
package base.day6;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
class Worker {
private int age;
Worker(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return age + "";
}
}
class MyComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
if(!(o1 instanceof Worker && o1 instanceof Worker)) {
throw new RuntimeException("No Worker!");
} else {
Worker w1 = (Worker)o1;
Worker w2 = (Worker)o2;
if(w1.getAge() == w1.getAge())
return 0;
else if(w1.getAge() > w2.getAge())
return 1;
else
return -1;
}
}
}
public class Demo15 {
/**
* @param args
*/
public static void main(String[] args) {
Set<Worker> set = new TreeSet<Worker>(new MyComparator());
set.add(new Worker(3));
set.add(new Worker(31));
set.add(new Worker(4));
set.add(new Worker(35));
set.add(new Worker(30));
System.out.println(set);
System.out.println(set.size());
}
}
以上代码,我想实现在控制台上按年龄升序打印set集合中的元素!!!!
结果居然是这个:
[3]
1
看到结果有种瞬间吊爆了的感觉。哪位大侠能发现问题!
|
|