我需要遍历 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;
}
另外,我如何使用 的版本初始化 String[] allkeys
j
我们在迭代完成后作为索引得到?
原文由 NoIdea 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于基本使用,HashMap 是最好的,我已经介绍了如何迭代它,比使用迭代器更容易:
快速解释:
意思是:“对于来自地图键的所有字符串,我们会做一些事情,并且在每次迭代中我们都会调用键’name’(它可以是你想要的任何东西,它是一个变量)
开始了 :