15,907,497 members
See more:
I have below question
Quote:
You are given the following sequence of numbers,
1, 652 ,5, 15, 385, 4 , 55, 666, 13, 2, 4658, 9, 55, -588, 10, 1083, 17 ,4.
You can remove the duplicate numbers by only using For loop and ArrayList .

And this is my output
```Before remove : [-588, 1, 2, 4, 4, 5, 9, 10, 13, 15, 17, 55, 55, 385, 652, 666, 1083, 4658]
[-588, 2, 4, 9, 13, 17, 55, 652, 1083]```
Some items are removed.

Edit
After I remove the sort method, my output as below
```Before remove : [1, 652, 5, 15, 385, 4, 55, 666, 13, 2, 4658, 9, 55, -588, 10, 1083, 17, 4]
[1, 5, 385, 55, 13, 4658, -588, 1083, 4]```

What I have tried:

```public class Ex {
public static void main(String[] args) {

ArrayList list = new ArrayList();

Collections.sort(list);

System.out.println("Before remove : " + list);

for (int i = 0; i < list.size(); i++) {
for (int j = 1; j < list.size(); j++) {
if (list.get(i) == list.get(j)) {
list.remove(j);
}
}
}
System.out.println(list);
}
}```
Posted
Updated 22-Oct-18 22:13pm
v4
Richard MacCutchan 23-Oct-18 4:26am
The problem arises because you are removing elements from the list within a loop that depends on list.size. So whenever you remove an item the number of elements is one less that the loop is expecting, so you will get the wrong results.

## Solution 1

You cannot use the `sort` method, the requirements don't allow it.
On the other hand you may use the `for` statement: two nested loops would do the trick.

[Update]

You have to carefully read the documentation[^]: 'Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).'
So, after a item removal, you have to deal with the new indices.
Moreover:
• The outer loop should stop at `(size()-1)`.
• The inner loop should start at `(i+1)`.

To summarize, try:
Java
```// ...

System.out.println("Before remove : " + list);

for (int i = 0; i < list.size()-1; ++i)
{
for (int j = i+1; j < list.size(); ++j)
{
if (list.get(i) == list.get(j))
{
list.remove(j);
--j; //deal with shifted indices
}
}
}
System.out.println(list);
```
[/Update]

v4
wseng 22-Oct-18 21:11pm
After remove the `sort` method, some of the items still get removed.
CPallini 23-Oct-18 3:21am
Well, show us your updated code.
wseng 23-Oct-18 4:12am
post updated.
CPallini 23-Oct-18 4:40am
Mine too.
wseng 23-Oct-18 6:11am
thanks,work like charm