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.
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.
Joined: May 27, 2008
Thanks all for the explanation.
Yes I think interviewer also wanted to hear the answer what Christophe had explained....
subject: How to avoid duplicate element in ArrayList?