I am using nested TreeMap
[UserMap [LibraryMap [BookMap]]
When I used BookMap.clear() instead of new , it clears all data and I remain with last 2 entered data in BookMap. Do I need to create new object ? I expect after adding the first BookMap and doing clear that won’t affect the LibraryMap but it did.
TreeMap<Integer, Integer> BookMap = new TreeMap<Integer, Integer>();
TreeMap<Integer, TreeMap<Integer, Integer>> LibraryMap = new TreeMap<Integer, TreeMap<Integer, Integer>>();
TreeMap<Integer, TreeMap<Integer, TreeMap<Integer, Integer>>> UserMap = new TreeMap<Integer, TreeMap<Integer, TreeMap<Integer, Integer>>>();
// Adding data to a tree map
BookMap.put(1, 2000);
BookMap.put(2, 2000);
BookMap.put(3, 2003);
LibraryMap.put(1,BookMap);
//BookMap.clear();
BookMap = new TreeMap<Integer, Integer>();
BookMap.put(4, 2006);
BookMap.put(5, 2007);
LibraryMap.put(2,BookMap);
BookMap= new TreeMap<Integer, Integer>();
BookMap.put(6,2009);
BookMap.put(7, 2012);
LibraryMap.put(3,BookMap);
UserMap.put(1,LibraryMap);
If you want to associate a new BookMap to a new key in LibraryMap, you need to create a new one.
If you use clear, your variable BookMap is still a reference to the instance you associated with key 1 in LibraryMap. In other words:
By the way, unrelated, but using a capital letter for a variable name is wrong: the convention is capital letter for Classes and lowcase for variables (bookMap).