Java: Avoid inserting duplicate in arraylist

后端 未结 6 1444
太阳男子
太阳男子 2020-11-29 08:56

I am novice to java. I have an ArrayList and I want to avoid duplicates on insertion. My ArrayList is

ArrayList karList         


        
6条回答
  •  攒了一身酷
    2020-11-29 09:04

    Use a HashSet instead of an ArrayList. But, to really make the HashSet really work well, you must override the equals() and hashCode() methods of the class/objects that are inserted into the HashSet.

    Foe example:

     Set set = new HashSet();
     set.add(foo);
     set.add(bar);
    
     public class MyObject {
         @Override
         public boolean equals(Object obj) {
             if (obj instanceof MyObject)
                 return (this.id = obj.id) 
             else
                 return false;
         }
         // now override hashCode()
    }
    

    Please see the following documentation for overriding hashCode() and equals().

提交回复
热议问题