java - Set.toString() 是如何实现的?

标签 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 方法?这是否意味着迭代器会调用此方法?

最佳答案

Set 是一个接口(interface)。
它不能覆盖方法。

您正在使用 HashSet ,它继承了 AbstractCollection.toString()

关于java - Set.toString() 是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5937869/

相关文章:

java - 如何在java中获取偏移值时在空格和特殊字符上分割字符串

java - SharedPreferences 不保存 boolean 值

java - 防止小程序打印安全警告

java - Zookeeper : Unsupported major. 次要版本 52.0

java - 如何检查一组矩形的孔洞和相互作用?

java - eclipse 3.8 : Call Hierarchy misses callers from jars

java - 将对象/整数插入单链表并对其进行排序

java - 使用Gson解析一个巨大的JSON对象,其中包含数组和对象?

java - 从刚刚发送的电子邮件中获取 ID

java - Libgdx file.internal 文件未找到错误