Friday, 4 September 2009

contains() Method In Arraylist Will Return False When Object Stored In List Changes Later

Couple of days back i and my collegue Sachin Mehta came across a problem and i thought of sharing to my readers.

Please remember that contains() method returns false whenever object in the list stored previously has been modified later.Once modified when we try to call contains() method in the list it fails :-)

Ex:


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ListDemo
{

public static void main(String[] args)
{
List<StudentTO> studentList=new ArrayList<StudentTO>();

StudentTO studentVerifier=new StudentTO();
studentVerifier.setAddress("address1");
studentVerifier.setName("name1");

StudentTO student1=new StudentTO();
student1.setAddress("address1");
student1.setName("name1");

StudentTO student2=new StudentTO();
student2.setAddress("address2");
student2.setName("name2");

studentList.add(student1);
studentList.add(student2);

boolean containsStudent1=studentList.contains(studentVerifier);
System.out.println("containsStudent1---: "+ containsStudent1);

student1.setAddress("NewAddress1");

containsStudent1=studentList.contains(studentVerifier);
System.out.println("containsStudent1---: "+ containsStudent1);
}
}

class StudentTO implements Serializable {

private String name;
private String address;
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}

@Override
public boolean equals(Object elem) {

System.out.println("entered equals()");

StudentTO rhs=null;

if(elem==null) return false;

if(elem instanceof StudentTO)
rhs=(StudentTO)elem;
else
return false;

if(this.getName().equalsIgnoreCase(rhs.getName()) && this.getAddress().equalsIgnoreCase(rhs.getAddress()))
return true;
else
return false;

}

}



Output:

entered equals()
containsStudent1---: true
entered equals()
entered equals()
containsStudent1---: false

Hope this small example helps if any

No comments: