此类按名称排序,但是当各种对象具有相同名称时会发生什么?
public class MyStuff implements Comparable<MyStuff> {
MyStuff(String n, int v){ name = n; value=v;}
String name; int value;
public int compareTo(MyStuff m){
return name.compareTo(m.name);
}
public String toString() { return name + " " + value + " ";}
public static void main(String[] args){
List<MyStuff> l = new ArrayList<MyStuff>();
MyStuff m0 = new MyStuff("hola",1);
MyStuff m1 = new MyStuff("hola",1);
MyStuff m2 = new MyStuff("hola",2);
MyStuff m3 = new MyStuff("hola",2);
l.add(m0);
l.add(m1);
l.add(m2);
l.add(m3);
Collections.sort(l);
System.out.println(l);
for(Object o: l) System.out.println(o.hashCode());
}
}
结果:
[hola 1 , hola 1 , hola 2 , hola 2 ]
21722195
12719253
30758157
12773951
哪个对象是第一个?取决于值,哈希码..?