Monday 7 October 2013

Textual description of firstImageUrl

What Is Wrong With This Program

Here's the Main Class called Question :
package com.test;

import java.util.HashSet;

public class Question {
 public static void main(String[] args) {
  HashSet uniqueObjects = new HashSet();
  TestObject obj1= new TestObject();
  TestObject obj2= new TestObject();


Here's The TestObject Class :
package com.test;

public class TestObject {
 private int id ;
 public boolean equals(Object other)
  if (other == null)
   return false;
  if (other == this)
   return true;
  if (!(other instanceof TestObject))
   return false;
  TestObject otherObject = (TestObject)other;
  if( == otherObject.getId())
   return true;
  return false;

 public int getId() {
  return id;

 public void setId(int id) { = id;


The program storing unique objects in the hash set , based on the id .

Can you figure out what is wrong with this program and why ?

Solution :

The problem with this code is , hash set is supposed to store only unique values by using equals method which we have already overridden , but it does not work as expected , so even if you enter two object with same id , size of hash set come as 2 instead of 1 .

The reason behind this is , to find out two object are equal or not , hash set first compares the hash code of two objects . If the hash codes are not equal , objects will not be considered equal , and it will not even use the equals method . In our case we have not overridden the hashCode method , so it will use the default hashcode method of object class , which returns memory address of objects in hex , since these two are different objects , so hashCode value will not be matched , even if equals method returns true . So we need to implement hashcode method also .