本帖最后由 孙胜 于 2013-5-4 11:59 编辑
看看我做的实验。透彻的分析了下HashSet的特点:- package demo;
- import java.util.*;
- public class Demo3 {
- public static void main(String[] args) {
-
- Collection<TwoPoint> c=new HashSet<TwoPoint>();
- TwoPoint t1=new TwoPoint(3,5);
- TwoPoint t2=new TwoPoint(3,6);
- TwoPoint t3=new TwoPoint(3,7);
-
- c.add(t1);
- c.add(t2);
- c.add(t3);
-
- System.out.println("集合的大小是:"+c.size());
- System.out.println("t1的hashcode是:"+t1.hashCode());
- System.out.println("t2的hashcode是:"+t2.hashCode());
- System.out.println("t3的hashcode是:"+t3.hashCode());
-
- t2.y=8;
-
- //测试修改后t2的hashcode
- System.out.println("t2的hashcode是:"+t2.hashCode());
-
-
- //不管是调用contains还是remove都会在集合中先去找t2的
- //显然没有找到。所以这两个方法都是false
- System.out.println(c.contains(t2));
- System.out.println(c.remove(t2));
-
-
- System.out.println("集合的大小是:"+c.size());
-
-
- //如果把这里改成5
- t2.y =5;
- System.out.println(c);
- //看结果是[3...5, 3...5, 3...7]。
- //此时t2的hashcode和集合中t1的相同,但是t2在集合中的hashcode并不改变,不论这个对象的hashcode是多少
-
-
- c.remove(t2);
- System.out.println(c);
- //这个时候你remove(t2),我觉得删除的是t1,t2永远都删除不掉了
-
- //验证t1已经删除了
- System.out.println(c.remove(t1));
- }
- }
- class TwoPoint{
- //覆写了hashCode()方法
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + x;
- result = prime * result + y;
- return result;
- }
- //覆写了equals()方法
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- TwoPoint other = (TwoPoint) obj;
- if (x != other.x)
- return false;
- if (y != other.y)
- return false;
- return true;
- }
- int x;
- int y;
- TwoPoint(int x,int y){
- this.x=x;
- this.y=y;
- }
- public String toString(){
- return x+"..."+y;
- }
- }
复制代码 输出结果:
集合的大小是:3
t1的hashcode是:1059
t2的hashcode是:1060
t3的hashcode是:1061
t2的hashcode是:1062
false
false
集合的大小是:3
[3...5, 3...5, 3...7]
[3...5, 3...7]
false
|