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
是一个接口(interface)。
它不能覆盖方法。
您正在使用 HashSet
类,它继承了 AbstractCollection.toString()
关于java - Set.toString() 是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5937869/