Java: Avoid inserting duplicate in arraylist

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

    Whenever you want to prevent duplicates, you want to use a Set.

    In this case, a HashSet would be just fine for you.

    HashSet karSet = new HashSet();
    karSet.add(foo);
    karSet.add(bar);
    karSet.add(foo);
    System.out.println(karSet.size());
    //Output is 2
    

    For completeness, I would also suggest you use the generic (parameterized) version of the class, assuming Java 5 or higher.

    HashSet stringSet = new HashSet();
    HashSet intSet = new HashSet();
    ...etc...
    

    This will give you some type safety as well for getting items in and out of your set.

提交回复
热议问题