• Post Reply Bookmark Topic Watch Topic
  • New Topic

Removing duplicates in an ArrayList  RSS feed

 
Werner Holt
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hej all! I am stuck on this exercise and I don't know what exactly is wrong. I think it's something with the .remove and the for each loop, but I am not sure.
Please help!


this is what i get
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at seven.removeDuplicates(seven.java:24)
at seven.main(seven.java:18)
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The ArrayList class doesn't allow you to remove() elements, via the ArrayList itself, while you are iterating through the list. To remove elements, you need to use the iterator's remove() method, as you are iterating through.

With your use-case, it is probably better to just not use an iterator.

Henry
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot use a for-each loop to assign elements, add them or remove them.

Add all the elements to a Set. There is a Set implementation which records the insertion order of its elements. Use that. Then create a new List to return from that Set, using the appropriate array list constructor.

Find out about Streams. They only work in Java8 It would be something like
newList = myList.stream().distinct().collect(Collectors.toList());

Don't declare variables of type ArrayList. Declare them as List which gives you much more flexibility.
 
Giovanni Montano
Ranch Hand
Posts: 434
7
Android Open BSD Slackware
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Werner Holt wrote:Hej all! I am stuck on this exercise and I don't know what exactly is wrong. I think it's something with the .remove and the for each loop, but I am not sure.
Please help!

HI Werner at the moment my coefficient of reliability is 0,3 but please consider that in a real life situation you could like to remove duplicates using HashSet
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!