我有一些奇怪的行为。
[更新:给出完整的可运行示例:]
package finaltestwithenummapentry;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.Map.Entry;
public class FinalTestWithEnumMapEntry {
enum SomeEnum{
ONE, TWO, THREE;
}
public static void main(String[] args) {
EnumMap<SomeEnum, Integer> map = new EnumMap<SomeEnum, Integer>(SomeEnum.class);
map.put(SomeEnum.ONE, 1);
map.put(SomeEnum.TWO, 2);
map.put(SomeEnum.THREE, 3);
ArrayList<Entry<SomeEnum, Integer>> entryList = new ArrayList<Entry<SomeEnum, Integer>>();
for(final Entry<SomeEnum, Integer> entry : map.entrySet()){
System.out.println("Key is " + entry.getKey() + ", value is " + entry.getValue());
//This prints the correct keys and values
entryList.add(entry);
}
System.out.println("");
for(Entry<SomeEnum, Integer> entry:entryList){
System.out.println("Key is " + entry.getKey() + ", value is " + entry.getValue());
//This prints only the last entry each time
}
}
}
输出(JavaSE 1.6):
Key is ONE, value is 1
Key is TWO, value is 2
Key is THREE, value is 3
Key is THREE, value is 3
Key is THREE, value is 3
Key is THREE, value is 3
我假设是最终的My entry
,似乎每次都被下一个覆盖。我每次都需要能够捕获正确的条目,因为我将每个项目传递给for
循环内的匿名内部类实例。
[更新:Java 7 中不存在此问题,只有 Java 6(可能更早)]
更新:无论是针对 Java 6 还是 7 编译,我都可能必须让我的代码工作,那么在这两种情况下让它工作的最有效的解决方法是什么?