0

I have a method and I want avoid inserting duplicates in my arraylist which already has data in it. I am not sure if this is right:

 private static Kar karNameExist(Kar kar, ArrayList<Kar> karList) {
    if (karList.contains(kar.getInsertKar())){
        System.out.println(“Kar name exists”);
    }
return kar;
}
3
  • Have you tried it? It will be faster to try it than to ask here and wait for answers. Commented Sep 25, 2013 at 20:46
  • 1
    What does kar.getInsertKar() do? Commented Sep 25, 2013 at 20:46
  • 2
    If you don't want duplicates, can I suggest using a Set? Commented Sep 25, 2013 at 20:46

2 Answers 2

1

You can LinkedHashSet instead of ArrayList to avoid duplicate entry

Sign up to request clarification or add additional context in comments.

Comments

0

If you have ArrayList<Kar>, you want to say karList.contains(kar) to check if kar is already contained in the list. To make this work, you must implement proper hashCode() and equals(Object) in your Kar class (so ArrayList "knows" how to properly compare objects of type "Kar"

1 Comment

Can yoiu please help me on this for coding? I am novice to java.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.