File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How to avoid duplicate element in ArrayList? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to avoid duplicate element in ArrayList?" Watch "How to avoid duplicate element in ArrayList?" New topic

How to avoid duplicate element in ArrayList?

Rahul Sud

Joined: May 27, 2008
Posts: 25
Hi All,

How to avoid duplicate element/Values in ArrayList?This was interview question.
My Answer was better to use Set in place of ArrayList.When collection framework has such facility better to use that to avoid duplicate elements.

But interviewer was said no i want it only in ArrayList.I suggest to use equals and override it with hashcode and make some sort of comparison and just pick one and set in the ArrayList.

Then without any expression interviewer move to next question.

Please share me your inputs to this question.I answered on the basis of hit and trial there because never came across such scenario in real world application.

Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

The simplest answer could be that, to avoid duplicate elements, you can check if it's already in the list ! By calling the contains method.

[My Blog]
All roads lead to JavaRanch
Raza Mohd
Ranch Hand

Joined: Jan 20, 2010
Posts: 247

hi ,

There is another alternate . Suppose you have a List object "listObject" and you want the Collection that does not have duplicate element.
then you can have this.

Set<String> setObject = new HashSet<String>(listObject);

It will give you a Set with bno duplicate elements.

or either you can use Christophe method.
For checking the elemnet in list.


Good luck!!
A small leak can sink a Gigantic ship.>
Steve Harney

Joined: Jun 19, 2010
Posts: 19

Dont be afraid to ask for clarifications in interviews, There are more than one right answer to most interview questions, if you say that you want to use a hashset and they ask to only use an ArrayList you should ask is there any particular reason for using an ArrayList.

From what you say it sounds like they where looking for the contains method like Christophe said.

I personally would have gone down a similar route to your answer, maybe with a LinkedHashSet, instead of a HashSet as it maintains order.

Rahul Sud

Joined: May 27, 2008
Posts: 25
Thanks all for the explanation.
Yes I think interviewer also wanted to hear the answer what Christophe had explained....
I agree. Here's the link:
subject: How to avoid duplicate element in ArrayList?
jQuery in Action, 3rd edition