The 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 方法?这是否意味着迭代器调用此方法?
Set
是一个接口。
它不能重写方法。
您正在使用HashSet
class,它继承了AbstractCollection.toString() http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractCollection.java#AbstractCollection.toString%28%29
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)