Java List ArrayList override equals method - Java @ Desk

Thursday, January 9, 2014

Java List ArrayList override equals method

Java List/ArrayList override contains method using equals
java.util.List() - A List is an ordered collection i.e. it maintains the insertion order. List is allowed to contain duplicate elements in it.
java.util.ArrayList() - This class implemented the list interface methods.

When we add String, Integer or any Wrapper class objects into an ArrayList, using the contains() method we can check is the ArrayList object contains the value or not.

In case, it is required that the list not to contains duplicates {you anyways can use java.util.Set interface} then in above case before adding any value, a contains() method can be called for that value.

Consider a scenario where you have custom java object and there is an ArrayList object of that object type i.e. generic type. In this case, contains method will not work, since it checks for object references. In order to achieve contains implementation for custom java object for List/ArrayList than in the custom java object equals() method need to be overridden.

Consider below class
Person
{ 
 String name;
 String address;
}

Create Person object with name = "Kumar", address = "Mumbai";
Add this in the List. Before adding in the list, perform a check if it contains or not. To achieve the correct implementation, Person class must override equals() method as shown below

@Override
    public boolean equals(Object o) {
        if (o instanceof Person) {
            System.out.println("List already contains this object");
            return name.equals(((Person) o).name) && age == ((Person) o).age && address.equals(((Person) o).address);
        }
        return false;
    }
Check below the complete implementation:

Person.java
package com.pojo;

public class Person {

    private int age;

    public String name;

    protected String address;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Person) {
            if (name.equals(((Person) o).name) && age == ((Person) o).age && address.equals(((Person) o).address)) {
                System.out.println("List already contains this object with Name - " + name + ", Address - " + address
                        + " & Age - " + age);
                return true;
            }
        }
        return false;
    }
}



Main Class For Testing
import java.util.ArrayList;
import java.util.List;

import com.pojo.Person;

public class ListContainsOverride {

    public static void main(String args[]) {
        Person person = new Person();
        person.setName("Kumar");
        person.setAddress("Mumbai");
        person.setAge(25);

        Person person1 = new Person();
        person1.setName("Kumar");
        person1.setAddress("Mumbai");
        person1.setAge(25);

        List<Person> persons = new ArrayList<Person>();
        
        // Before adding an object, check if it not contains
        // Adding Person Object
        if (!persons.contains(person)) {
            persons.add(person);
        }
        
        // Before adding an object, check if it not contains
        // Adding Person1 Object with same values
        if (!persons.contains(person1)) {
            persons.add(person1);
        }

        System.out.println("\nFinal List \n");
        for (Person person2 : persons) {
            System.out.println("Name - " + person2.getName());
            System.out.println("Address - " + person2.getAge());
            System.out.println("Age - " + person2.getAddress());
        }
    }
}

Output
List already contains this object with Name - Kumar, Address - Mumbai & Age - 25

Final List 

Name - Kumar
Address - 25
Age - Mumbai







3 comments:

  1. Thanks for the tutorial but according to Java specifications, there is a contract between equals and hashCode methods. If you are overriding one of them, you must override the other one else you are breaking the contract hence your code may not work correctly. Even though this is an example, you should override the hashCode as well.

    ReplyDelete
    Replies
    1. I need to check because the code is thoroughly tested before posting here. Will cross check.

      Delete
  2. Anonymous @June 23, 2014 at 12:49 AM is correct and you should always override equals() and hashCode() at the same time.

    Without modifying both at the same time you will end up with behaviours that are unexpected at run time. For your example this may work, however other collection classes may not work as you expect (specifically Map classes that use the hashCode function to determine equality).

    ReplyDelete