有没有一种方法可以递归地遍历 aHashMap
使得value1
ofkey1
实际上是新的,它再次key2
返回value2
,将是下一个key3
,依此类推......直到它返回null
?逻辑如下:
hm.get(key)
hm.get(hm.get(key))
hm.get(hm.get(hm.get(key)))
......
我假设这可以通过一些递归过程来完成?如果我错了,请纠正我。谢谢!
这是你想要的程序吗?它将通过遍历 hashmap 返回最终值:
Public Object traverseMap(Object key)
while(hm.get(key) != null){
key = hm.get(key);
}
return key;
}
如果以这种方式设置散列图(即它包含一个值,该值也是另一个值的键),那将是可能的。您可以在递归方法中执行此操作,但循环就足够了:
Object key = someInitialKey;
Object value = null;
do {
value = hm.get( key );
key = value;
} while( value != null );
好吧,无论如何,这就是您要求的(尾巴!)递归版本:
public class Qsdf {
public static Object traverseMap(Map m, Object key) {
return traverseMap(m, key, new HashSet());
}
public static Object traverseMap(Map m, Object key, Set traversed) {
if (key == null) { // first key has to be null
throw new NullPointerException();
}
traversed.add(key);
Object value = m.get(key);
if (traversed.contains(value)) { // added after Stephen C's comment on other answer
// cycle found, either throw exception, return null, or return key
return key;
}
return value != null ?
traverseMap(m, value, traversed) :
key; // I guess you want to return the last value that isn't also a key
}
public static void main(String[] args) {
final HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
m.put(0, 1);
m.put(1, 2);
m.put(3, 4);
m.put(2, 3);
final Object o = traverseMap(m, 0);
System.out.println(o);
}
}