java HashSet应用

来源:互联网 发布:云付网页源码 编辑:程序博客网 时间:2024/05/17 06:49

        在使用HashSet时,应注意:一、自己的类有属性,就应当重写方法equals和hashCode;二、写方法时要遵守的原则,两个类equals返回true时,hashCode一定相等(考虑一下哈希表的冲突就可以理解);三、在使用时不得随意修改HashSet中的值,否定将会导致结果不准确性。

import java.util.*;class R{public 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 TestHashSet{public static void main(String[] args){HashSet hs = new HashSet();hs.add(new R(5));hs.add(new R(-3));hs.add(new R(9));hs.add(new R(-2));System.out.println(hs);Iterator it = hs.iterator();R first = (R)it.next();first.count = -3;//直接改变,最好先删除再插入System.out.println(hs);hs.remove(new R(-3));//只查找到了原先的-3System.out.println(hs);System.out.println("has -3 " + hs.contains(new R(-3)));//falseSystem.out.println("has -5 " + hs.contains(new R(-5)));//false}}



原创粉丝点击