A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© z_one 中级黑马   /  2015-11-6 14:12  /  352 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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)));
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马