重写哈希集合的方法

class A {
    int count;
    
    public A() {
        super();
        // TODO Auto-generated constructor stub
    }

    public A(int count) {
        this.count = count;
    }

    public String toString() {
        return "A[count:" + count + "]";
    }

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o != null && A.class == o.getClass()) {
            A a = (A) o;
            return this.count == a.count;
        }
        return false;
    }

    public int hashCode() {
        return this.count;
    }
}

public class HashSetTest2 {
    public static void main(String[] args) {
        HashSet hs = new HashSet();
        hs.add(new A(4));
        hs.add(new A(-3));
        hs.add(new A(8));
        hs.add(new A(9));
//        hs.forEach(System.out::print);
        Iterator it = hs.iterator();
        A first = (A)it.next();
        first.count = 5;//把第一个元素修改为5注意不要修改成与原来集合元素相同的值,这样会造成哈希集合的混乱
        hs.forEach(System.out::println);
        hs.remove(new A(4));
        System.out.println(hs);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值