Deep compare sets in Java

后端 未结 2 1241
不知归路
不知归路 2021-01-11 17:22

I have two sets in Java that compare Item objects. Is there a method to compare the sets so that Item\'s equals method is invoked and

2条回答
  •  失恋的感觉
    2021-01-11 18:27

    This is the default behaviour, if it's not what you're seeing then check that you're overriding hashCode as well. See the following code for an example:

    public static void main(String[] args) {
        Set items1 = new HashSet();
        items1.add(new Item("item 1"));
        items1.add(new Item("item 2"));
    
        Set items2 = new HashSet();
        items2.add(new Item("item 1"));
        items2.add(new Item("item 2"));
    
        System.out.println(items1.equals(items2));
    }
    
    private static class Item {
        private String id;
    
        public Item(String id) {
            this.id = id;
        }
    
        @Override
        public int hashCode() {
            return id.hashCode();
        }
    
        @Override
        public boolean equals(Object obj) {
            return id.equals(((Item)obj).id);
        }
    } 
    

    This outputs:

    true

提交回复
热议问题