我编写了这段代码,试图制作一个具有地图的对象。

public class MyClass {
    private static Map<String, List<String>> myMap;

    public MyClass() {
        myMap = new TreeMap<String, List<String>>();
    }
    public void putValueInMap() { //etc... }
    public void toString() { //etc...}
}


但是,当我尝试制作两个对象时,它们似乎是同一对象!

public class Driver {
public static void main(String[] args) {
    System.out.println("Testing Constructor: ");
    MyClass nope = new MyClass();
    MyClass wut = new MyClass();

    System.out.println("nvl" + nope.toString());
    System.out.println("wut" + wut.toString());

    try {
        nvl.addValue("this is a", "test");
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("****added this is a:test****");
    System.out.println("nope" + nvl.toString());
    System.out.println("wut" + wut.toString());

}

}


我得到的输出是:

Testing Constructor:
nope[]
wut[]
****added this is a:test****
nope[this is a:test]
wut[this is a:test]


为什么nope和wut引用相同的对象?

最佳答案

MyMapstatic,表示它是MyClass的每个实例中使用的同一对象。如果删除static修饰符,则每个实例将获得自己的Map

08-04 22:50