toString()
方法在Set
或其層次結構中沒有被覆蓋,所以元素是如何打印的?Set.toString()如何實現?
import java.lang.Math;
import java.util.HashSet;
class Hello{
public String name= "";
Hello(String name){
this.name = name;
}
public static void main(String args[]){
Hello h1 = new Hello("first");
Hello h2 = new Hello("second");
Hello h3 = new Hello("third");
Hello h4 = new Hello("fourth");
Hello h5 = new Hello("fourth");
HashSet hs = new HashSet();
hs.add(h1);
hs.add(h2);
hs.add(h3);
hs.add(h4);
hs.add(h5);
//hs.add(h5);
//hs.add(null);
System.out.println("elements in hashset"+hs);
//System.out.println("elements in hashset"+hs.contains());
//System.out.println("elements in hashset"+hs.contains(new Hello("who")));
}
public boolean equals(Object obj){
System.out.println("In Equals");
System.out.println(name+"=====equals======"+((Hello)obj).name);
if(name.equals(((Hello)obj).name))
return true;
else
return false;
}
public int hashCode(){
System.out.println("----In Hashcode----"+name);
return name.hashCode();
}
}
Output :----In Hashcode----first ----In Hashcode----second ----In Hashcode----third ----In Hashcode----fourth ----In Hashcode----fourth In Equals fourth=====equals======fourth ----In Hashcode----fourth ----In Hashcode----second ----In Hashcode----third ----In Hashcode----first elements in hashset[[email protected], [email protected] ]
而且當我打印的HashSet的hashCode方法被調用每一個元素?這是否意味着迭代器調用此方法?
那麼很顯然你沒有檢查整個層次結構。請參閱AbstractCollection類。 – Manoj 2011-05-09 13:59:25
我只看到代碼(種)而沒有問題。 – Marcelo 2011-05-09 13:59:49
@Manoj:不;他正在檢查錯誤的層次結構。 'Set'不會繼承'AbstractCollection'。 – SLaks 2011-05-09 14:00:04