According to the documentation list contains is supposed to use equals(). Meaning, it should return true if of the values within the object are the same. However, in the example below contains(Object) behave differently:
import java.util.ArrayList;
import java.util.List;
public class Dog{
private String name;
private int age;
private String colour;
public Dog(String name, int age, String colour){
this.name = name;
this.age = age;
this.colour = colour;
}
public static void main(String []args){
List<String> names = new ArrayList<>();
String name1 = "adam";
names.add(name1);
System.out.println(names.contains(new String("adam"))); //returns true
List<Dog> dogs = new ArrayList<>();
Dog fido = new Dog("fido", 2, "black");
dogs.add(fido);
System.out.println(dogs.contains(new Dog("fido", 2, "black"))); // returns false
}
}
Why does it return true when a new String object is compared but not when a new Dog object is compared?
I know I can probably fix this by overriding contains(Object), but curious to know why this does not work by default.
List<Dog> dogs = new ArrayList<>();
Dog fido = new Dog("fido", 2, "black");
dogs.add(fido);
System.out.println(dogs.contains(new Dog("fido", 2, "black")));
return false because of Hashcode And Equals are not implemented in DOG Custom class. In java.lang.String class, hashCode() method is also overridden so that two equal string objects according to equals() method will return the same hash code values.