我对使用Map.Entry接口感到困惑。我发现了一个使用Map.Entry的示例,如下所示,但如果在其类的末尾添加了"implements Map.Entry“,则会返回错误。此外,接口不应该实现其方法,但在此接口中实现了5个方法(equals、getKey、getValue、hashCode、setValue)。有人能解释一下这是怎么回事吗?
此外,根据Oracle的Java教程,“如果您的类声称实现了一个接口,那么在该类成功编译之前,该接口定义的所有方法必须出现在其源代码中。”因此,我猜既然下面的示例不需要实现Map.Entry接口,那么就不需要实现Oracle的Java API中列出的5个方法。但是为什么呢?
import java.util.HashMap;
import java.util.*;
class Dog {
String color;
Dog(String c) color = c;
public boolean equals(Object o)
return ((Dog) o).color.equals(this.color);
public int hashCode()
return color.length();
public String toString()
return color + " dog";
}
public class TestHashMap {
public static void main(String[] args) {
HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
Dog d1 = new Dog("red");
Dog d2 = new Dog("black");
Dog d3 = new Dog("white");
Dog d4 = new Dog("white");
hashMap.put(d1, 10);
hashMap.put(d2, 15);
hashMap.put(d3, 5);
hashMap.put(d4, 20);
//print size
System.out.println(hashMap.size());
//loop HashMap
for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey().toString() + " - "+ entry.getValue());
}
}
}发布于 2015-02-13 13:30:05
正如视图Map.entrySet()中返回的那样,Map.Entry是一个键值对。您的类Dog正被用作一个键;它不是,也不需要是一个Map.Entry。Map.Entry的实现通常是Map本身的实现细节。你很少需要实现一个。
https://stackoverflow.com/questions/28492977
复制相似问题