如何实现Set.toString()? [英] How is Set.toString() implemented?
本文介绍了如何实现Set.toString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
toString()
方法未在 Set
或其层次结构中重写,那么元素是如何打印的?
The toString()
method is not overridden in Set
or its hierarchy, so how are the elements printed?
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方法吗?这是否意味着迭代器调用了这个方法?
Also When I print hashset the hashcode method is called for each of the elements ?Does it mean the iterator calls this method ?
推荐答案
Set
是一个接口。
它无法覆盖方法。
Set
is an interface.
It cannot override methods.
您正在使用 HashSet
类,它继承了 AbstractCollection.toString()
You're using the HashSet
class, which inherits AbstractCollection.toString()
这篇关于如何实现Set.toString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文