I read in a article that java contains method uses indexOf method which internally uses equals method to check if object is present in string.
So i have a code and i haven't overriden the equals method for Employee class.
Employee employee = new Employee(1,"John");
Employee employee2 = new Employee(1,"akshay");
Employee employee3 = new Employee(1,"akshay");
List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee3);
employeeList.add(employee);
System.out.println(employeeList.contains(employee)); // returns true
System.out.println(employee3.equals(employee2)); // returns false
System.out.println(employeeList.contains(new Employee(1,"akshay"))); // returns false
Why does the contains method returns true if it uses equals method internally? As the equals method is checking for reference equality by default how does contains method finds out if the object exists or not?
Why does the contains method returns true if it uses equals method internally?
The default behaviour of equals
would return true when both objects refer to the same object. This is what happening in your code.
Employee employee = new Employee(1, "John");
....
List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee);
....
System.out.println(employeeList.contains(employee));
The last line loops through each Employee in the list and calls the equals on it. When it encounters John, it would be like checking employee.equals(employee)
which is true.
For the last two calls to return true, you have to override equals and hashCode method.