黑马程序员技术交流社区

标题: HashSet中的hashcode值的问题 [打印本页]

作者: z_one    时间: 2015-11-6 14:12
标题: HashSet中的hashcode值的问题
HashSet中是通过hashCode和equals()来判断的,可是我通过(t.count=3)将对象newTest(1)的hashCode设置成为了3,那为什么System.out.println(hs.contains(new Test(3)));输出为false
代码如下 :
import java.util.*;
class Test {
        int count;
        public Test(){

        }
        public Test(int count){
                this.count = count;
        }
        @Override
        public boolean equals(Object otherObject){
                if(this == otherObject)
                        return true;
                if(otherObject == null)
                        return false;
                if(getClass() !=  otherObject.getClass())
                        return false;
                Test other = (Test) otherObject;
                return this.count == other.count;
               
        }
        @Override
        public int hashCode(){
                return this.count;
        }
}
public class HashCodeTest{
        public static void main(String[]args){
                HashSet hs = new HashSet();
                hs.add(new Test(1));
                hs.add(new Test(2));
                hs.add(new Test(3));

                System.out.println(hs);

                Iterator it = hs.iterator();
                Test t = (Test) it.next();
                t.count = 3;
                System.out.println(hs);
                System.out.println(hs.remove(new Test(3)));
                System.out.println(hs);
                System.out.println(hs.contains(new Test(3)));
                System.out.println(hs.contains(new Test(1)));
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2