When you say you have a list. Do you mean you have: List<Person> person;
?
Because you say you are trying to use contains
. Contains compares objects, not values in objects.
For example if I had an ArrayList of strings.
ArrayList<String> colors = new ArrayList<>;
And I had some strings like:
String a = "red";
String b = "blue";
String c = "green";
String d = "green";
Then added a,b,c to the ArrayList, but left out d.
colors.add(a);
colors.add(b);
colors.add(c);
With the objects now in the arraylist. I can use compare like this:
colors.contains(a)
This will return true because the object 'a' is in the ArrayList. But if you try colors.contains(d)
it'll return false. Even though the value of 'c' is 'green' which is the same value as 'd'. It isn't the same object. Because '.contains()' is just comparing objects and not the value of the object.
If you want to compare the values of a list/arrayList than you will have to a For loop.
public boolean comparePerson(ArrayList<Person> persons, Person person) {
//persons is your main list. And person is a single person that you want to see if they are in the ArrayList.
for (Person p: persons) {
if (person.name == p.name) {
if (person.address == p.address) {
return true;
}
}
}
return false;
}
Optionally this is why having an Id field is useful. You'll only need to compare Ids and not multiple fields for a confident match.