开发者

How is Set.toString() implemented?

The toString() method is not overridden in Set or its hierarchy, so how are the elements printed?

import java.lang.Ma开发者_开发百科th;
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
]

Also When I print hashset the hashcode method is called for each of the elements ?Does it mean the iterator calls this method ?


Set is an interface.
It cannot override methods.

You're using the HashSet class, which inherits AbstractCollection.toString()


The Set implementations inherit toString from AbstractCollection. The Set elements are output as a string list separated by commas.


HashSet does returns comma separated strings as overrided by its super class AbstractSet.

No surprises!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜