2011-05-09 15 views
6

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方法被調用每一個元素?這是否意味着迭代器調用此方法?

+1

那麼很顯然你沒有檢查整個層次結構。請參閱AbstractCollection類。 – Manoj 2011-05-09 13:59:25

+0

我只看到代碼(種)而沒有問題。 – Marcelo 2011-05-09 13:59:49

+0

@Manoj:不;他正在檢查錯誤的層次結構。 'Set'不會繼承'AbstractCollection'。 – SLaks 2011-05-09 14:00:04

回答

7

的Set實現從AbstractCollection繼承的toString。 Set元素以逗號分隔的字符串列表形式輸出。

+0

另外當我打印hashset時,爲每個元素調用hashcode方法嗎?它是指迭代器調用這種方法? – crackerplace 2011-05-09 14:11:22

+0

'hashCode()'在'HashMap'的get和put方法中被調用,'HashSet'在內部使用(實際上是'LinkedHashMap')。如果您有興趣,請參閱http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java。 – 2011-05-09 14:41:30

+0

@ lee3lite OK .... – crackerplace 2011-05-09 17:53:33

1

HashSet的確實通過其超一流的overrided AbstractSet.

沒有意外逗號分隔字符串的回報!

+0

對不起,遲到的迴應。問題在2分鐘前回答。 – 2011-05-09 14:02:22