
Patrick K. answered 04/04/19
Computer Science and Programming Tutor (Python, Java, C)
There are really 2 way to do this, depending on your space/time complexity requirements. One thing to watch out for is a ConcurrentModification exception; you don't want to remove elements from an ArrayList while you're iterating over said ArrayList.
Here are the 2 options:
- Convert your ArrayList to an array. Then iterate over the array with a nested while loop that removes duplicates of an element from the ArrayList while that element exists in the ArrayList. If you're in school and your teacher/professor has not told you about HashSets or has explicity told you not to use HashSets then this would be the way to go. Otherwise, this is bad practice as this method takes quadratic time and linear space.
- The best way to do this would be to create a LinkedHashSet by passing the ArrayList to its constructor. Then convert the LinkedHashSet to an ArrayList. The LinkedHashSet will remove duplicates for you and maintain the order of the elements in your list. This method takes linear time and linear space, certainly better than the previous example.