HashSet contains duplicate entries

后端 未结 4 700
Happy的楠姐
Happy的楠姐 2020-12-03 17:33

A HashSet only stores values ones, when the equals method says that they\'re the same. Thats what I thought.

But now i\'m adding Elements to a HashSet where the equa

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 18:03

    If you have your own model classes you need to change some basic functions work like done in the below example.

    Execution code :

    HashSet models = new HashSet();
    
    for (int i = 1; i < 5; i++)
        models.add(new MyModel(i + "", "Name :" + i + ""));
    
    for (int i = 3; i < 5; i++)
        models.add(new MyModel(i + "", "Name :" + i + ""));
    
    for (Object object : models)
        System.out.println(object);
    

    Model Class :

    /**
     * Created by Arun
     */
    public static class MyModel {
    
        private String id = "";
        private String name = "";
    
        public MyModel(String id, String name) {
            this.id = id;
            this.name = name;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return getId();
        }
    
        @Override
        public boolean equals(Object obj) {
            return !super.equals(obj);
        }
    
        public int hashCode() {
            return getId().hashCode();
        }
    
    }
    

    Hope this helps.

提交回复
热议问题