Java: Avoid inserting duplicate in arraylist

后端 未结 6 1447
太阳男子
太阳男子 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:02

    A set is simply a collection that can contain no duplicates so it sounds perfect for you.

    It is also very simple to implement. For example:

    Set mySet = new HashSet();
    

    This would provide you a set that can hold Objects of type String.

    To add to the set is just as simple:

    mySet.add("My first entry!");
    

    By definition of a set, you can add whatever you want and never run into a duplicate.

    Have fun!

    EDIT : If you decide you are dead-set on using an ArrayList, it is simple to see if an object is already in the list before adding it. For example:

    public void addToList(String newEntry){
        if(!myList.contains(newEntry))
            myList.add(newEntry);
    }
    

    Note: All my examples assume you are using String objects but they can easily be swapped to any other Object type.

提交回复
热议问题