Prev: Call for Papers Reminder (extended): The World Congress on Engineering WCE 2010
Next: JDBC Connection Issue
From: Patricia Shanahan on 9 Mar 2010 10:55 Javas wrote: .... > > Above code outputs : 2 > But I thought it is supossed to be 1 since the hashcode is the same > for both the objects, equals also holds true and the set doesnt allow > duplicates. What is wrong? Please correct me. Of all the issues that have been pointed out, I think the primary problem is the failure to override hashCode. The inherited Object hashCode method is likely to return different codes for distinct, but equal, objects. HashSet depends on equal objects having the same hashCode result. I prefer to use an IDE, such as Eclipse, and have it create the skeleton for any method I intend to be an override. Even if you are using command line and editor, you can put in the @Override annotation, causing a compile time error if your method does not override anything. Making hashCode return 1 for every instance is a good debug technique while trying to work out what is going on. Just make sure you fix it before working with more than a handful of elements in your HashSet. The following is a modified version of your program that uses @Override, corrects the spelling of "hashCode", adds declarations of p1 and p2, and does an additional add to the HashSet to demonstrate treatment of both equal and unequal elements. import java.util.*; public class Qn353 { private String name; public Qn353(String name) { this.name = name; } public boolean equals(Object o) { if ( ! (o instanceof Qn353) ) return false; Qn353 p = (Qn353) o; return p.name.equals(this.name); } public static void main(String [] args) { HashSet<Object> hs = new HashSet<Object>(); Qn353 p1 = new Qn353("A"); Qn353 p2 = new Qn353("A"); hs.add(p1); hs.add(p2); System.out.println(hs.size()); Qn353 p3 = new Qn353("B"); hs.add(p3); System.out.println(hs.size()); } @Override public int hashCode() { return 1; } }
First
|
Prev
|
Pages: 1 2 Prev: Call for Papers Reminder (extended): The World Congress on Engineering WCE 2010 Next: JDBC Connection Issue |