Java-集合练习题(HashSet添加机制)

Java-集合练习题(HashSet添加机制)

  • 韩顺平Java视频中的练习题,坑挺多的,mark一下;
class Person{

    int id;
    String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    //根据id和name属性重写了hashCode()和equals()
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return id == person.id && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

@SuppressWarnings("all")
public class practices06 {
    public static void main(String[] args) {
        Set set = new HashSet();
        Person p1 = new Person(1001, "AA");
        Person p2 = new Person(1002, "BB");
        set.add(p1);
        set.add(p2);
        //此时,set中有两个元素:
        //		1.索引hashCode(1001, "AA")====>p1{1001, "AA"};
        //		2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
        p1.name = "CC";
        //此时,set中的两个元素为:
        //		1.索引hashCode(1001, "AA")====>p1{1001, "CC"};
        //		2.索引hashCode(1002, "BB")====>p2{1002, "BB"};

        set.remove(p1);
        //由于remove()方法删除时,是删除set中索引为hashCode(1001, "CC")处的元素,由于该处没有元素,remove()没有删除任何元素;

        System.out.println(set);
        //打印set中的两个元素:
        //		1.索引hashCode(1001, "AA")====>p1{1001, "CC"};
        //		2.索引hashCode(1002, "BB")====>p2{1002, "BB"};

        set.add(new Person(1001, "CC"));
        //此时,set中的三个元素为:
        //		1.索引hashCode(1001, "AA")====>p1{1001, "CC"};
        //		2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
        //		3.索引hashCode(1001, "CC")====>{1001, "CC"};

        System.out.println(set);
        //打印set中的三个元素:
        //		1.索引hashCode(1001, "AA")====>p1{1001, "CC"};
        //		2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
        //		3.索引hashCode(1001, "CC")====>{1001, "CC"};
        
        set.add(new Person(1001, "AA"));
		//此时,set中的四个元素为:
        //		1.索引hashCode(1001, "AA")====>p1{1001, "CC"} ====>{1001, "AA"};
        //		2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
        //		3.索引hashCode(1001, "CC")====>{1001, "CC"};
        
        System.out.println(set);
        //打印set中的四个元素为:
        //		1.索引hashCode(1001, "AA")====>p1{1001, "CC"} ====>{1001, "AA"};
        //		2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
        //		3.索引hashCode(1001, "CC")====>{1001, "CC"};
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SEA-365

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值