因为你使用的是TreeSetTreeSet 要求你加入的对象能够比较大小,而你的MyClass无法比较假如你把 MyClass 实现 Comparable 就可以了如:
public class MyClass implements Comparable {
public int a;
public String s;
public int compareTo(Object o) {
return s.compareTo(((MyClass)o).s);
}
}
public class MyClass implements Comparable {
public int a;
public String s;
public int compareTo(Object o) {
return s.compareTo(((MyClass)o).s);
}
}
TreeSet 的 API中有说明
add
public boolean add(Object o)Adds the specified element to this set if it is not already present.
Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in the set.当然除了象上面我修改以后那样你可以选择使用 HashSet