【发布时间】:2017-08-18 07:30:08
【问题描述】:
我需要遍历BucketMap 并获取所有keys,但是我如何在不手动操作的情况下获得buckets[i].next.next.next.key 之类的东西,因为我在这里尝试过:
public String[] getAllKeys() {
//index of string array "allkeys"
int j = 0;
String allkeys[] = new String[8];
//iterates through the bucketmap
for (int i = 0; i < buckets.length; i++) {
//checks wether bucket has a key and value
if (buckets[i] != null) {
//adds key to allkeys
allkeys[j] = buckets[i].key;
// counts up the allkeys index after adding key
j++;
//checks wether next has a key and value
if (buckets[i].next != null) {
//adds key to allkeys
allkeys[j] = buckets[i].next.key;
j++;
}
}
}
return allkeys;
}
另外,如何使用迭代完成后获得的j 版本作为索引来初始化String[] allkeys?
【问题讨论】:
-
您还可以阅读 JavaDoc for Map 以了解获取所有键的更简单方法...
-
你能给出bucket的定义吗?
-
嗯,这是一张地图。它有一个键、一个值和下一个。
-
所以你创建了一种 LinkedMap ?为什么不使用现有的实现?
-
所以如果它是一个 Map,只需获取 keySet() 并通过 for(String key : bucketMap.ketSet()){ /* 条目类型例如 List、Map、Class 等进行迭代这里的地图值*/ ) = bucketMap.get(key) } 即 Map
> 将是 List = buckeyMap.get(key);
标签: java loops hashmap iterator initialization