除非您使用集合作为地图的值,否则您将无法为特定存储区使用多个值。检查什么put()
将在文档做HashMap
使用清单作为映射值,你可以尝试以下方法:
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Playground {
public static void main(String[] args) {
Map<Integer, List<Pair>> map = new LinkedHashMap<Integer, List<Pair>>();
map.put(1, Arrays.asList(new Pair(10, 1) , new Pair(100, 2)));
map.put(2, Arrays.asList(new Pair(2, 1)));
map.put(3, Arrays.asList(new Pair(3, 5), new Pair(6, 10), new Pair(9, 15), new Pair(12, 18)));
for (Map.Entry<Integer, List<Pair>> entry : map.entrySet()) {
System.out.println(String.format("Bucket %d has %d item(s)", entry.getKey(), entry.getValue().size()));
}
}
}
class Pair {
Integer x;
Integer y;
Pair(Integer x, Integer y) {
this.x = x;
this.y = y;
}
}
输出将是如下:
Bucket 1 has 2 item(s)
Bucket 2 has 1 item(s)
Bucket 3 has 4 item(s)
希望有帮助
我不认为这回答了我的问题(或者我问的问题不是很清楚)。让我们假设,我有一个bucket大小为5的hashmap/hashtable。为了计算hashcode,我使用mod 5运算符作为散列函数。前5个键即1,2,3,4,5将占据桶1到5.当我将键6和一些值一起插入时,它将被添加到桶1.因此,桶1的大小现在为2。是我正在寻找的。 – Ram27 2014-11-04 02:47:15
我明白你的意思了。我不认为这些桶的信息会被暴露。快速检查[源代码](http://www.docjar.com/html/api/java/util/HashMap.java.html),您需要的信息就在那里,只是不公开提供。 – 2014-11-04 03:24:22
谢谢,只是在同一页面上,你是指addEntry/createEntry方法? – Ram27 2014-11-04 05:46:21