小编Lau*_*fel的帖子

意外的HashSet等于行为

这是Java 8中发生奇怪行为的代码段:

 @Test
    public void test() {
        DummyPojo dummyPojo1 = DummyPojo.of("1", "A");
        DummyPojo dummyPojo2 = DummyPojo.of("2", "B");

        Set<DummyPojo> set1 = new HashSet<>();
        set1.add(dummyPojo1);

        Set<DummyPojo> set2 = new HashSet<>();
        set2.add(dummyPojo2);

        System.out.println("dummyPojo1 == dummyPojo2 should be false = " + (dummyPojo1.equals(dummyPojo2)));
        System.out.println("set1 == set2             should be false = " + (set1.equals(set2)));

        dummyPojo1.setAttribute1(dummyPojo2.getAttribute1());
        dummyPojo1.setAttribute2(dummyPojo2.getAttribute2());

        System.out.println("dummyPojo1 == dummyPojo2 should be true  = " + (dummyPojo1.equals(dummyPojo2)));
        System.out.println("set1 == set2             should be true  = " + (set1.equals(set2)));//WRONG
        System.out.println("set2 == set1             should be true  = " + …
Run Code Online (Sandbox Code Playgroud)

java equals hashset

0
推荐指数
1
解决办法
40
查看次数

标签 统计

equals ×1

hashset ×1

java ×1