我写了这段代码,试图制作一个有地图的对象。
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 引用同一个对象?