Reputation: 11
I wrote this code, trying to make an object that has a map.
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...}
}
But when I try to make two of the object, they seem to be the same object!
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());
}
}
The output I'm getting is:
Testing Constructor:
nope[]
wut[]
****added this is a:test****
nope[this is a:test]
wut[this is a:test]
Why are nope and wut referencing the same object?
Upvotes: 0
Views: 60
Reputation: 5516
Static variable will be associated with the class and not with the object reference. so irrespective of the number of object you create, you will be having only one copy of static variable.
to point the map to different reference you have to change it from static to instance variable
Upvotes: 0
Reputation: 44448
MyMap
is static
, meaning it is the same object used in every instance of MyClass
. If you remove the static
modifier, each instance will get its own Map
.
Upvotes: 4