2016-02-17 38 views
-2

考虑一类在此基础上做的SortedSet排序在JAVA

public Test 
{ 
    int a; 
    int b; 

    Test(int a,int b) { 
     this.a=a; 
     this.b=b 
    } 

    public static void main(String args[]) { 
     Test test1 = new Test(1,2); 
     Test test2 = new Test(2,1); 
     SortedSet<Test> set = new TreeSet<Test>(); 
     set.add(test1); 
     set.add(test2); 
    } 
} 

现在,如果我通过名为setSortedSet迭代,其中test1test2会更早遇到,为什么?

+2

从文档中的第二句话:“这些元素是使用它们的自然顺序进行排序的,或者是通过在有序集创建时提供的比较器进行排序的。”在*请求堆栈溢出帮助之前,请执行研究*。 –

+1

您的'Test'类不是'Comparable '(它不'执行'),也没有向'TreeSet'构造函数提供'Comparator '的实例。不确定你的意思,或者你的问题是什么。 –

+0

你有没有在询问之前运行你的代码?我不认为你的代码工作。你可以在问之前谷歌搜索吗?! –

回答

1

当您运行此代码,因为您的Test类未实现Comparable<Test>你会得到一个异常(一ClassCastException),所以有一个为TreeSet,以便用它来保持你的排序元素Test不自然顺序。例外情况将发生在set.add(test1)

当使用TreeSet,您必须通过将要素类实现Comparable或使用TreeSet构造函数接受Comparator指定排序。