More efficient way to remove elements from an array list

前端 未结 3 416
说谎
说谎 2021-01-25 12:45

I have developed a array list something like this

ArrayList list = new ArrayList();
list.add(\"1\");
list.add(\"8\");
list.add(\"8\"         


        
相关标签:
3条回答
  • 2021-01-25 12:58

    If you need to store the duplicates I suggest you to use Map<Integer,Integer> where the 1st Integer is the key and the 2nd is the number of key occurences . So when you add the key that already exists you just increment the corresponding counter. (In remove operation you doing vice - versa). When you need all the distinct values, you just use Map.keySet().

    0 讨论(0)
  • 2021-01-25 13:23

    Performance wise they should be similar. Have you tested? If you want to use the built in methods, you can do this with a similar performance.(to be confirmed by testing):

    list.removeAll(Arrays.asList("8"));
    

    Finally if you want a list without duplicates, use a Set as others have mentioned.

    0 讨论(0)
  • 2021-01-25 13:23

    If you just need a set of numbers, then use HashSet and not a List. If you need to preserve the order by which you are putting the numbers, use LinkedHashSet. As for removal, always prefer the version with the iterator, even though in your particular case the performance may be comparable. The idiom with iterator is more widely applicable than indexing, for example if you used a LinkedList, indexing would result in disastrous performance.

    0 讨论(0)
提交回复
热议问题