-1

Can i use contains() to check if an element i m trying to insert in an Arraylist is already there?

protected void addTeacher(Teacher t){
        if (!(teacherList.contains(t)))
            teacherList.add(t);
    }

I have created a teacher class. Thanks,

3 Answers3

1

Yes, you can use contains method.You will need to implement equals() method if you are after meaningful(i.e. both objects have same value for all fields) equality and not just object references.

Look here at Oracle docs: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)

G.G.
  • 592
  • 5
  • 16
1

in your Teacher class you should override equals method and define for the program what is your strategy for the equality of two objects. Then you can perfectly use contains method.

Take note a better solution is to use Set.

a Set never save a duplicate object within it. for using a Set you should override both equals and hashCode methods.

refer to this thread, I explained everything clearly for someone else with similar question -> equals and hashCode methods

Mehdi
  • 3,795
  • 3
  • 36
  • 65
  • Thanks. Why should i use set, if in an arraylist i only have to overriede one method(equals) and with set have to to override two of them? – Pedro Mateus Dec 02 '18 at 02:58
  • @PedroMateus The overrides is within the Teacher class only, that's the strategy of dealing with Set collection in java. but once you override those two methods, you're all set and you can use any type of Set flavor, like HashSet. The equals and hashCode methods can be generated by your IDE automatically. please refer to the link I put inside the answer. If you want to know more about Set collections in java refer to this link -> https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html – Mehdi Dec 02 '18 at 03:02
0

Yes, using .contains() should work for your case. However, depending on what the rest of your code looks like, you might want to consider using something other than ArrayLists. For example, if you use a set, you won't have to do .contains() because set can't hold duplicates.

akmin04
  • 677
  • 6
  • 14