这里我们可以看到Map.Entry toString()方法的实际应用。 自Map.Entry是一个接口以来定义的位置。
import java.util.*;
import java.lang.*;
import java.io.*;
class Dog
{
public int i;
public int hashCode()
{
return i%3;
}
Dog(int i)
{
this.i = i;
}
public String toString()
{
return i + "" ;
}
}
class ShellClass
{
public static void main (String[] args) throws java.lang.Exception
{
HashMap m = new HashMap(5,(float)0.8);
for(int i=1; i<=4; i++)
{
m.put((new Dog(i)),"dog");
}
System.out.println(m); // line1
Set entrySet = m.entrySet();
System.out.println(entrySet); // line2
Iterator itr = entrySet.iterator();
while(itr.hasNext())
{
Map.Entry element = (Map.Entry)itr.next();
System.out.println(element); // line3
}
}
}
我得到以下输出:
{3=dog, 1=dog, 4=dog, 2=dog} //output by line 1
[3=dog, 1=dog, 4=dog, 2=dog] //output by line 2 Map.Entry toString in action
3=dog // output by line 3 (Map.Entry toString in action)
1=dog // output by line 3 (Map.Entry toString in action)
4=dog // output by line 3 (Map.Entry toString in action)
2=dog // output by line 3 (Map.Entry toString in action)
你能告诉我Map.Entry toString()方法在哪里实现
答案 0 :(得分:1)
在我的java标准库的参考实现中,HashMap
中有一个静态内部类,它隐含Map.Entry
接口。
无论好坏,内心阶层都是&#34;也是&#34;名为Entry
。
你可以看到它here。其toString
implementation看起来像这样:
public final String toString() {
return getKey() + "=" + getValue();
}