2
for (int i = 0; i < arrayP.size(); i++) {

        if (arrayP.get(i) == What to put here?) {
              arrayP.remove(i)
        }
}

If I put i+1 it just compares side by side. How can I get it to run through each element?

Element 1 then run through the whole ArrayList. Then element 2 run through ArrayList.

3
  • 2
    @JarrodRoberson That question is simply about detecting whether duplicates are present, not about removing them. Commented Sep 1, 2013 at 1:02
  • ArrayList#removeAll? Commented Sep 1, 2013 at 1:34
  • Not a duplicate. I have voted to reopen. Commented Sep 1, 2013 at 8:48

2 Answers 2

7

You can use a LinkedHashSet:

list = new ArrayList<>(new LinkedHashSet<>(list));

If the order of elements does not matter, you should use a normal HashSet instead. In fact, if it's logical to do so, you might consider using a Set instead of a List in the first place. Read about the differences between the two and pick the structure that's more appropriate.

Sign up to request clarification or add additional context in comments.

1 Comment

+1. Not only removed duplicates, but also preserved the initial order of elements in list.
0

try this

Set arrayPSet = new LinkedHashSet(arrayP);

now arrayPSet holds your array removing it's duplicate values, then you can use it, you can re-assign your list to this set once again, like

arrayP = new ArrayList(arrayPSet);

now duplicates are removes

just make sure to override the equals() and hashCode() methods if arrayP list holds objects created by you

ok, i updated it maybe this works, i didnt try the order issue, but there are TreeSet/Comparators/Comparables solutions , just try this modification first

2 Comments

Fail. Changes the order of the elements of the ArrayList.
@StephenC: I don't see how that's a hard and fast requirement, per se...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.