黑马程序员技术交流社区
标题:
请教在用hash集合时重写hashCode的排序问题?
[打印本页]
作者:
李成航
时间:
2012-3-15 15:50
标题:
请教在用hash集合时重写hashCode的排序问题?
本帖最后由 李成航 于 2012-3-15 15:51 编辑
如果我重写hashCode()方法,并让他返回同一个整数值,那此时的hash集合将如何排序?如下例子:
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(int a){this.age=a;}
public int hashCode(){return 9;}//始终返回同一个整数9
}
public class Test{
public static void main(String[] args){
HashSet hs=new HashSet();
hs.add(new Student(4));
hs.add(new Student(1));
hs.add(new Student(2));
hs.add(new Student(3));
hs.add(new Student(3));
Iterator it=hs.iterator();
while(it.hasNext()){
System.out.println(((Student)it.next()).getAge());//此时输出顺序是按什么排序的?
}
}
}
不知它是按什么排序的?因为此时每个对象的hash码重写后的返回值是相同的.
作者:
foxpeter
时间:
2012-3-15 15:55
set 集合本来就没有顺序啊 只是集合里的每个元素都唯一而已
要有顺序的话就用Treeset吧
作者:
段浩亮
时间:
2012-3-15 16:03
HashSet是无序的 存入顺序和取出顺序是不一样的 无法事先确定取出顺序
要想对集合进行排序,可以用TreeSet 也可以用Collections中的sort()方法对List集合进行排序 前提是List集合中的对象必须继承Comparable并复写compareTo()方法或者传递自定义的比较器
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2