I'm having some strange behaviour.
[UPDATE: Full runnable example given:]
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
}
}
}
Output (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
, which I'm presuming is final, is seemingly overwritten by the next one each time. I need to be able to capture the correct entry each time, as I am passing each item to an anonymous inner class instance inside the for
loop.
[UPDATE: This problem doesn't exist in Java 7, only Java 6 (and maybe before) ]
UPDATE: I might have to make my code work whether it's compiled against Java 6 or 7, so what's the most efficient workaround for making it work in either case?