0

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

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 引用同一个对象?

4

2 回答 2

4

MyMapstatic,这意味着它是在 的每个实例中使用的相同对象MyClass。如果您删除static修饰符,每个实例将获得自己的Map.

于 2013-09-07T01:44:56.953 回答
0

静态变量将与类相关联,而不是与对象引用相关联。因此,无论您创建的对象数量如何,您都只会拥有一份静态变量。

要将地图指向不同的引用,您必须将其从静态更改为实例变量

于 2013-09-07T01:55:45.123 回答