Wednesday, July 9, 2008

Design Concept - Secrets of contains() method in Vector and ArrayList

How .contains() method works?

When you store strings into a Vector or ArrayList, you tend to use .contains() method to check if the given string is found in the list or not. If found the method returns true and false when not found.

But when you try the same when you store your own objects, say DTOs and other user-defined objects, it does not work. Why? This is a practical-sceanario many people struggle and get confused when the contents are same but the result is false. Let us analyse. Here we go...

The secret behind .contains() method is the .equals() method in Object class. Because, internally, the contains() method uses equals() method to check the equality. For String objects, it uses by default and checks if the contents are same or not. But for the user-defined objects, it checks if the equals() method is defined for the object or not. If there is no equals() method defined, it uses default equals method that checks if the references (address) of these objects are same or not. As a result, you find that always false is returned though the property values are same. So the solution is to override equals() method for the object you are trying to store into Vector and ArrayList.

Let us see an example:

public class User
{
String userName;
String password;

public void setUserName(String userName)
{
this.userName = userName;
}

public void setPassword(String password)
{
this.password = password;
}

public String getUserName()
{
return userName;
}

public String getPassword()
{
return password;
}

public boolean equals(Object obj)
{
if (! (obj instanceof User)) // If objects are of different type, return false
return false;
User user = (User) obj; // Cast the object to User type.
// Find if the userName and password are same in both objects.
return (this.userName.equals(user.userName) && this.password.equals(user.password) );
}

}


Demo of using the .contains method:

Vector users = new Vector();
User x = new User(); x.setUserName(“Swathika”); x.setPassword(“Swathika”);
User y = new User(); y.setUserName(“Swathika”); y.setPassword(“Swathika”);
User z = new User(); z.setUserName(“Swathika”); z.setPassword(“Swathika”);
users.add(x);
users.add(y);
System.out.println(“The equality :” + users.contains(z))

The result would be

The equality : true

So, take care when you use Vector and Arraylist to store user-defined objects. Let us see some more design concepts and lot more in articles to come. In the next blog, we will see how to use inheritance and how to use base class and super class effectively, in practical scenarios. Please keep visiting my blog.

Regards,
Swathika.

1 comment:

Santi's Blog said...

hi, its always a best practice to define equals() and hashcode() method for any user defined class.
Refer to the java docs for the cotract to be followed for both these methods.

Nice blogs