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();
  obj1.setId(1);
  
  TestObject obj2= new TestObject();
  obj2.setId(1);
  
  uniqueObjects.add(obj1);
  uniqueObjects.add(obj2);
  
  System.out.println(uniqueObjects.size());
  
 }
 
 

}


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


public class TestObject {
 
 private int id ;
 
 
 @Override
 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(this.id == otherObject.getId())
   return true;
  
  return false;
 }


 public int getId() {
  return id;
 }


 public void setId(int id) {
  this.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 .