L
lowenbrau
Hi,
I have a class Obj. I created three objects o1,o2,03. Objects are equal if their id is equal. For example, o1 and o3 are equal. I tried adding these three objects to a HashSet, and when I print the size of the hashset I get "3" and not "2". Something is not right with the equals or hashcode method. Can someone shed some light?
code snippet:
import java.util.*;
public class Test
{
public static void main (String[] args)
{
Set hs = new HashSet();
Obj o1 = new Obj ("w", 10);
Obj o2 = new Obj ("r", 20);
Obj o3 = new Obj ("w", 30);
hs.add(o1);
hs.add(o2);
hs.add(o3);
System.out.println(hs.size());
}
public static class Obj
{
String id;
int length;
Obj (String id, int length)
{
this.id = id;
this.length = length;
}
boolean equals (Obj o)
{
if (o == null)
return false;
else if (o instanceof Obj)
return (this.id.equals(o.id));
else return false;
}
public int hashCode()
{
return id.hashCode();
}
}
}
I have a class Obj. I created three objects o1,o2,03. Objects are equal if their id is equal. For example, o1 and o3 are equal. I tried adding these three objects to a HashSet, and when I print the size of the hashset I get "3" and not "2". Something is not right with the equals or hashcode method. Can someone shed some light?
code snippet:
import java.util.*;
public class Test
{
public static void main (String[] args)
{
Set hs = new HashSet();
Obj o1 = new Obj ("w", 10);
Obj o2 = new Obj ("r", 20);
Obj o3 = new Obj ("w", 30);
hs.add(o1);
hs.add(o2);
hs.add(o3);
System.out.println(hs.size());
}
public static class Obj
{
String id;
int length;
Obj (String id, int length)
{
this.id = id;
this.length = length;
}
boolean equals (Obj o)
{
if (o == null)
return false;
else if (o instanceof Obj)
return (this.id.equals(o.id));
else return false;
}
public int hashCode()
{
return id.hashCode();
}
}
}