以下代码因NullPointerException
in main失败(map==null)
。仅当我定义 2001 或更多枚举常量时才会出现此问题,2000 工作正常。
为什么不执行静态代码块?
我们是否达到了编译器(无警告、无错误)或 JVM 的任何静默限制?
编译出来的class文件超过172KB,
import java.util.HashMap;
public enum EnumTest {
E(1),E(2),...,E(2001);
private static HashMap<Integer, EnumTest> map = new HashMap<Integer, EnumTest>();
static {
for ( EnumTest f : EnumTest.values() ) {
map.put( (int) f.id, f );
}
}
short id;
private EnumTest(int id) {
this.id = (short) id;
};
public short getId() {
return id;
}
public static final EnumTest fromInt(int id) {
EnumTest e = map.get( id );
if ( e != null ) {
return e;
}
throw new IllegalArgumentException( "" + id );
}
public static void main(String[] args) {
System.out.println( "size:" + map.size() );
}
}
运行环境:
java version "1.7.0_01" Java(TM) SE Runtime Environment (build 1.7.0_01-b08) Java HotSpot(TM) 64-Bit Server VM (build 21.1-b02, mixed mode)
也发生在:
java version "1.6.0_32" Java(TM) SE Runtime Environment (build 1.6.0_32-b05) Java HotSpot(TM) Client VM (build 20.7-b02, mixed mode, sharing)