我试图在Java 8中使用Hashmap。我将使用哈希函数来获取索引,以放置给定键和值的节点,但如果有相同键的节点,我必须使用Linked List那种数据结构。然而,如果有相同键的节点,我必须使用Linked List类型的数据结构。这是我感到困惑的地方。
例如,如果有
package First;
import java.util.HashMap;
public class MyClass extends Node {
public MyClass(int k, int v) {
super(k, v);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
HashMap<String, Node> capitalCities = new HashMap<String, Node>();
capitalCities.put("England", new Node(1,3));
capitalCities.put("Germany", new Node(1,3));
capitalCities.put("Norway", new Node(1,3));
capitalCities.put("USA", new Node(1,3));
capitalCities.put("USA", new Node(1,3));
System.out.println(capitalCities);
}
}
如果我打印h1,它只有 "APPLE",13所以我想把Hashmap做成这样:"APPLE",1 ->;"APPLE",10 ->;"APPLE",13。
字符串类的哈希码和等价方法使得 "APPLE "具有唯一性。所以,你需要把对象作为一个键或使用StringBuilder代替String。像下面这样
Map<StringBuilder, Integer> h1 = new HashMap<>();
h1.put(new StringBuilder("APPLE"), 1);
h1.put(new StringBuilder("APPLE"), 10);
h1.put(new StringBuilder("APPLE"), 13);
System.out.println(h1);