如果我访问 LinkedHashMap<Vector, Vector<Integer>>
的 key 在其类中,它被正确提取,但如果我创建其类的实例并调用显示 LinkedHashMap 的类方法,我会发现作为 Vector 实例的键中的一些字段丢失。
import java.util.Vector;
import java.util.LinkedHashMap;
public class TestLinkedHashMap
{
public static void main(String[] args)
{
Test t = new Test();
t.setSample();
System.out.println("The sample printed in main function is : \n" + t.getSample());
return;
}
}
class Test
{
LinkedHashMap<Vector, Vector<Integer>> sample;
public Test()
{
sample =
new LinkedHashMap<Vector, Vector<Integer>>();
}
public LinkedHashMap<Vector, Vector<Integer>> getSample()
{
return sample;
}
public void setSample()
{
Vector record1 = new Vector();
record1.add(new String("Apple"));
record1.add(new String("Orange"));
record1.add(new String("Grapes"));
record1.add(new String("Lime"));
Vector<Integer> v1 = new Vector<Integer>();
v1.add(new Integer(0));
v1.add(new Integer(8));
v1.add(new Integer(28));
System.out.println("sample = " + sample);
sample.put(new Vector(record1), v1);
Vector record2 = new Vector();
record2.add(new String("Pineapple"));
record2.add(new String("Pear"));
record2.add(new String("Mango"));
Vector<Integer> v2 = new Vector<Integer>();
v2.add(new Integer(0));
v2.add(new Integer(18));
sample.put(new Vector(record2), v2);
System.out.println("The sample printed inside the class is : \n" + sample);
}
上面的代码工作正常,但在我正在开发的应用程序中,我得到了示例的不同输出。我在下面包含了我的应用程序的输出。我的应用程序以与上面类似的方式使用 LinkedHashMap。
实际应用中输出有所不同
最佳答案
当然this.sample
是 null
。您从未将其设置为值。在构造函数中,您将创建一个新的 LinkedHashMap<Vector, Vector<Integer>>
,但实际上并没有将其分配给类成员变量 sample
,相反,您只是创建一个名为 sample
的局部变量(构造函数的局部变量) .
删除LinkedHashMap<Vector, Vector<Integer>>
之前sample
在构造函数中,这将初始化类成员变量 sample
正如预期的那样。
关于java - LinkedHashMap 中的不同错误 - java8.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51035273/