如何实现Set.toString()?

时间:2011-05-09 13:55:28

标签: java

toString()或其层次结构中未覆盖Set方法,因此如何打印元素?

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[Hello@b4616a1a, Hello@c9
]

当我打印hashset时,会为每个元素调用hashcode方法吗?这是否意味着迭代器会调用此方法?

3 个答案:

答案 0 :(得分:22)

Set是一个界面 它无法覆盖方法。

您使用的是HashSet ,它继承了AbstractCollection.toString()

答案 1 :(得分:8)

Set实现从AbstractCollection继承toString。 Set元素输出为以逗号分隔的字符串列表。

答案 2 :(得分:1)

HashSet确实返回由超类AbstractSet.

覆盖的逗号分隔字符串

没有惊喜!