Java 难以理解嵌套集合
我正在使用字节码在java中动态生成类,然后加载该类。我在教程中找到了这段代码Java 难以理解嵌套集合,java,collections,nested,bytecode,Java,Collections,Nested,Bytecode,我正在使用字节码在java中动态生成类,然后加载该类。我在教程中找到了这段代码 private int stringConstant(String s) { return constant(CONSTANT_Utf8, s); } private int classConstant(String s) { int classNameIndex = stringConstant(s.replace('.', '/')); ret
private int stringConstant(String s) {
return constant(CONSTANT_Utf8, s);
}
private int classConstant(String s) {
int classNameIndex = stringConstant(s.replace('.', '/'));
return constant(CONSTANT_Class, classNameIndex);
}
private int constant(Object... data) {
List<?> dataList = Arrays.asList(data);
if (poolMap.containsKey(dataList))
return poolMap.get(dataList);
poolMap.put(dataList, poolIndex);
return poolIndex++;
}
private void writeConstantPool(DataOutputStream dout) throws IOException {
dout.writeShort(poolIndex);
int i = 1;
for (List<?> data : poolMap.keySet()) {
assert(poolMap.get(data).equals(i++));
int tag = (Integer) data.get(0);
dout.writeByte(tag); // u1 tag
switch (tag) {
case CONSTANT_Utf8:
dout.writeUTF((String) data.get(1));
break; // u2 length + u1 bytes[length]
case CONSTANT_Class:
dout.writeShort((Integer) data.get(1));
break; // u2 name_index
default:
throw new AssertionError();
}
}
}
private final Map<List<?>, Integer> poolMap =
new LinkedHashMap<List<?>, Integer>();
private int poolIndex = 1;
private int stringConstant(字符串s){
返回常数(常数μUtf8,s);
}
私有int类常量(字符串s){
int classNameIndex=stringConstant(s.replace('.','/');
返回常量(常量\u类,classNameIndex);
}
私有int常量(对象…数据){
List dataList=Arrays.asList(数据);
if(poolMap.containsKey(数据列表))
返回poolMap.get(数据列表);
poolMap.put(数据列表,pooldex);
返回pooldex++;
}
私有void writeConstantPool(DataOutputStream dout)引发IOException{
dout.writeShort(poolidex);
int i=1;
对于(列表数据:poolMap.keySet()){
assert(poolMap.get(data).equals(i++);
int标记=(整数)data.get(0);
dout.writeByte(标记);//u1标记
开关(标签){
外壳常数\u Utf8:
dout.writeUTF((字符串)data.get(1));
break;//u2长度+u1字节[长度]
案例常数\u类:
dout.writeShort((整数)data.get(1));
break;//u2 name\u索引
违约:
抛出新的断言错误();
}
}
}
私有最终映射,整数>();
私有int-poolidex=1;
我不明白包含列表的映射是如何被使用的,它看起来不像是一种传统的面向对象的方法来做这类事情。在您给我们的片段中,映射是一种将唯一索引(从1增加)分配给每个列表的方法。显然,此索引仅在
断言中使用,用于检查键的检索顺序是否与插入键的顺序相同-如果映射是链接的SHMAP
,则确实应该如此
就给定的代码而言,LinkedHashSet
也可以。当然,我们不知道在哪里调用常量
等,可能是调用程序使用了索引
从面向对象的角度来看,我看不到任何反对意见——首先,这个代码片段几乎没有面向对象。传统的面向对象方法做什么?你会怎么做?“这看起来不像是一种传统的面向对象的方式来做这类事情。”——为什么不呢?嵌套列表对象只是用作贴图关键点的对象。什么不是OOP?创建一个表示列表中的内容的类并将其用作键为什么会更好?您有一个类是列表。你会得到什么?编辑包含在地图中的列表会让人困惑