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.

informatik01
  • 16,038
  • 10
  • 74
  • 104

2 Answers2

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
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

Ahmed Adel Ismail
  • 2,168
  • 16
  • 23