日期:2014-05-20  浏览次数:20703 次

这个小程序输出结果令人费解,java设计不完善吗

class R{
int count;
public R(int count){
this.count=count;
}
public String toString(){
return "R(count属性:"+count+")";
}
public boolean equals(Object obj){
if(obj instanceof R){
R r=(R)obj;
if(r.count==this.count){
return true;
}
}
return false;
}
public int hashcode(){
return this.count;
}
}
public class TestSet {
public static void main(String[] args) {
HashSet<R> hs=new HashSet<R>();
hs.add(new R(5));
hs.add(new R(-2));
hs.add(new R(9));
hs.add(new R(-3));
System.out.println(hs);
Iterator<R> it=hs.iterator();
R first=it.next();
first.count=-3;
System.out.println(hs);
hs.remove(new R(-3));
System.out.println(hs);
System.out.println("hs是否包含count为-3的R对象?"+hs.contains(new R(-3)));
System.out.println("hs是否包含count为5的R对象?"+hs.contains(new R(5)));
}
}

------解决方案--------------------
1.永远不要怀疑JDK。
2.这一句hs.remove(new R(-3));  //你new一个对象又remove等于没有变化,你想remove的话应该写成:
    hs.remove(first);
3. hs.contains(new R(-3));  hs.contains(new R(5));  你刚new的对象又没有add到集合,必然是false。

建议你好好复习一下基础知识。把对象的引用和对象的初始化的概念理解清楚。
------解决方案--------------------
引用:
Quote: 引用:

1.永远不要怀疑JDK。
2.这一句hs.remove(new R(-3));  //你new一个对象又remove等于没有变化,你想remove的话应该写成:
    hs.remove(first);
3. hs.contains(new R(-3));  hs.contains(new R(5));  你刚new的对象又没有add到集合,必然是false。

建议你好好复习一下基础知识。把对象的引用和对象的初始化的概念理解清楚。

那我要查看集合中是否包含某个元素怎么写?

set集合是无序的,所以你没办法直接查。你可以通过:
  Iterator<R> it=hs.iterator();去遍历
while(it.hasNext()){
     Object obj=it.next();  //这样就得到了
}
你要想按索引能取到就用List集合。Set取不到。因为Set就没有get(index) 这个方法。
------解决方案--------------------
   public int hashcode(){
        return this.count;
    }

還是那句,你hashCode寫錯了
是hashCode不是hashcode
==============================================================

Iterator<R> it=hs.iterator();
        R first=it.next();

        first.count=-3;
還有這句極度有問題,set裡的這個元素可以說被你弄壞了
不過要說起來又要從一個很久很久的故事說起,樓主有心情還是自己去看看hash的原理
沒心情深究就記著改變和hash code/equals有關的值前先從 hash map/set里拿出來,改變了再放回去
------解决方案--------------------
故意写错个hashCode方法坑人纳?
------解决方案--------------------



引用:
Quote: 引用:


你要想按索引能取到就用List集合。Set取不到。因为Set就没有get(index) 这个方法。


R r1=new R(5);
R r2=new R(-3);
R r3=new R(9);
hs.add(r1);
hs.add(r2);
hs.add(r3);
可以这样查吧?!
System.out.println("hs是否包含r1对象?"+hs.contains(r1));
System.out.println("hs是否包含r2对象?"+hs.contains(r2));
System.out.println("hs是否包含r3?"+hs.contains(r3));

楼主如果这样使用,加上自己的hashCode重写方法名写对了的话,是可以得到true的。因为HashSet提供了contains这个方法,他也是通过将你传入的key进行hash,然后进行将Hashset里面的值进行比较,如果存在你则返回true。