Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to avoid duplicate element in ArrayList?

 
Rahul Sud
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.



Thanks,
Rahul
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Raza Mohd
Ranch Hand
Posts: 247
Java MyEclipse IDE MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


Regards!
Raza
 
Steve Harney
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Rahul,
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.

Steve.
 
Rahul Sud
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all for the explanation.
Yes I think interviewer also wanted to hear the answer what Christophe had explained....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic