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;
}
Beau Grantham
  • 3,435
  • 5
  • 33
  • 43
user2766131
  • 187
  • 1
  • 1
  • 7

2 Answers2

1

You can LinkedHashSet instead of ArrayList to avoid duplicate entry

Shamim Ahmmed
  • 8,265
  • 6
  • 25
  • 36
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"

Gyro Gearless
  • 5,131
  • 3
  • 18
  • 14