为什么TreeSet不接受重复的自定义对象,即使在自定义对象中没有覆盖equals和hashcode?

时间:2016-05-11 07:27:53

标签: collections set hashset treeset

public class Coll {
    public static void main(String[] args) {
        Set<Silver> set = new TreeSet<Silver>(new Gold());
        Silver silver = new Silver("1");
        Silver silver2 = new Silver("1");
        set.add(silver);
        System.out.println(set.add(silver2));
        System.out.println(set.size()); 
    }
}

class Silver {
    private String qty;

    public Silver(String qty) {
        this.qty = qty;
    }

    public String getQty() {
        return qty;
    }

    public void setQty(String qty) {
        this.qty = qty;
    }
}

class Gold implements Comparator<Silver> {
    public int compare(Silver obj1, Silver obj2) {
        return obj1.getQty().compareTo(obj2.getQty());
    }
}

0 个答案:

没有答案