Gaurav
Gaurav

Reputation: 3749

Unique ArrayList

I am using an arraylist that contains duplicate copies of object. I can determine the duplicate copies using lastIndexOf method. After determination, I can remove that duplicate item from list. Now, AFAIK, on removal of item from list, the overall structure of the list would get damaged. I mean if I remove item number 5 from list, then at location 5, nothing would be there which would utlimatly lead to traversing problem. I have read the stack overflow similar questions and tried every single one like hashset, for me, they dont work. How can I maintain a unique Arraylist containing string only.

Upvotes: 0

Views: 141

Answers (2)

Amir Afghani
Amir Afghani

Reputation: 38531

It pays to read the documentation.

public Object remove(int index)

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

As Mike mentioned, if duplicates are an issue, why not use a Set?

Upvotes: 0

Mike Hogan
Mike Hogan

Reputation: 10603

Location 5 will not contain "a hole" if you remove item 5. The next item in the list will become item 5, if there is one. So you can keep removing items from a list to achieve uniqueness. But if you want a unique collection, you could use a Set.

Upvotes: 3

Related Questions