有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的树集?

我很困惑(Java新手)

我知道:

TreeSet doesn't actually use equals() at all. It uses compareTo() instead - if compareTo() returns zero, that means the two objects are "equal" as far as the TreeSet is concerned.

太好了

所以我有:

public class User implements Comparable<User>
{
    String Username;
    String Password;


    @Override
    public int compareTo(User o)
    {
        return o.Username.compareTo(this.Username );
    }
}

我还有:

public static void main(String[] args)
    {
        TreeSet<User> ts = new TreeSet<User>();
        User u = new User();
        u.Username="u";
        ts.add(u);

        User u1 = new User();
        u1.Username="u";
        ts.add(u1);  //<---------------
        System.out.print(u1.compareTo(u)); //0


    }

查看调试:compareTo-返回“0”。(顺序相同)

如果是:

问题

当我插入2个“相同顺序”的元素时,为什么不出现异常


共 (2) 个答案

  1. # 1 楼答案

    请参见TreeSet^{}方法的文档

    If this set already contains the element, the call leaves the set unchanged and returns false.

    第二个元素(u1)实际上并没有添加到TreeSet

  2. # 2 楼答案

    将两个相同的元素添加到任何Set时,也没有例外。第一个加法将返回true

    boolean addU = ts.add(u); // returns true
    

    而第二个将返回false

    boolean addU1 = ts.add(u1);  // returns false
    

    请注意,当compareToequals不一致时,您的测试很难看到会发生什么,因为您依赖于java.lang.StringcompareTo方法,这与equals是一致的