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 ?