java - LinkedHashMap 中的不同错误 - java8.1

标签 java linkedhashmap

如果我访问 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.samplenull 。您从未将其设置为值。在构造函数中,您将创建一个新的 LinkedHashMap<Vector, Vector<Integer>> ,但实际上并没有将其分配给类成员变量 sample ,相反,您只是创建一个名为 sample 的局部变量(构造函数的局部变量) .

删除LinkedHashMap<Vector, Vector<Integer>>之前sample在构造函数中,这将初始化类成员变量 sample正如预期的那样。

关于java - LinkedHashMap 中的不同错误 - java8.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51035273/

相关文章:

java - 如何让 Maven 使用 Eclipse 工作区默认的 JRE?

java - 如何从 HashMap 或 LinkedHashMap 中获取有限数量的值?

java - 命令行参数导致 "main"线程中出现异常

java - SimpleDateFormat 解析时忽略月份

java - android.view.InflateException : Binary XML file line #22: Error inflating class ImageView

java - 如何将一个 Map 中的 K 和另一个 Map 中的 V 写入一个文件?

java - 如何保存 LinkedHashMap<Integer, Integer>?

java - 从 HashMap 获取值作为引用

java - 有没有办法实现LinkedHashMap的数组?

java - 如何设置android评分栏的高度和宽度?