理解TreeSet.add()方法

Set存放不同元素,TreeSet存放不同元素,并且对元素进行排序。

Set<Object> set = new TreeSet<Object>();
set.add(new Integer(18));
set.add(new String("Bruce")); //Error

上面代码有错吗?


以上代码会抛出以下异常
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

当add()一个元素时,需要对元素进行排序,因此会强制转换类型进行比较。

结论:add()相同的类型

class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return this.name + " " + this.age;
}
}

Set<Object> set = new TreeSet<Object>();
set.add(new User("David", 25));
set.add(new User("Bruce", 26)); //Error

以上代码会抛出以下异常
Exception in thread "main" java.lang.ClassCastException: src.User cannot be cast to

java.lang.Comparable

结论:需要实现Comparable接口

JDK中实现了Comparable接口的类有:
BigDecimal、BigInteger、Byte、Double、Float、Integer、Long、Short
Character
String



class User implements Comparable {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return this.name + " " + this.age;
}
public int compareTo(Object o) {
User other = (User)o;
if (this.name.compareTo(other.name) > 0) return 1;
if (this.name.compareTo(other.name) < 0) return -1;
return 0;
}
}
public class Test {
    public static void main(String[] args){
    Set<Object> set = new TreeSet<Object>();
//创建5个不同对象
    set.add(new User("Phil", 25));
    set.add(new User("Admin", 25));
    set.add(new User("Bruce", 26));
    set.add(new User("Phil", 43));
    set.add(new User("Bruce", 37));
    for (Iterator it = set.iterator(); it.hasNext();) {
    System.out.println(it.next());
    }
    }
}
/**Output:
Admin 25
Bruce 26
Phil 25
*/
排序成功了,但是却少了2个对象。因为当compareTo()方法返回0时(即排序相等),TreeSet的add()方法会认为已经存在该对象,于是不加到集合当中。

你可能感兴趣的:(java,jdk,thread)