Code
Public Static void Main(string[] args) {testlist (); }/** * Test if HashMap need clone * 1, do you think the print out ID is 1 or 2? * 2, the size of the list is 1 or 2? Is the ID of each map a 1 or a 2? * 3, ID will be 4? * * @since 2015.7.12 * * Private Static void testlist() {list<map<string, string>> List =NewArraylist<map<string, string>> (); map<string, string> map =NewHashmap<string, string> (); Map.put ("id","1"); List.add (map); TestMap (list); System.out.println ("1, =========== id="+ List.get (0). Get ("id")); TESTMAP2 (list); System.out.println ("2, =========== size="+ list.size ()); System.out.println ("Id="+list.get (0). Get ("id")); System.out.println ("Id="+list.get (1). Get ("id")); TESTMAP3 (list); System.out.println ("3, =========== id="+ List.get (0). Get ("id")); }Private Static void TestMap(list<map<string, string>> List) {map<string, string> Map = List.get (0); Map.put ("id","2"); }Private Static void TESTMAP2(list<map<string, string>> List) {map<string, string> Map = List.get (0); Map =NewHashmap<string, string> (); Map.put ("id","3"); List.add (map); }Private Static void TESTMAP3(list<map<string, string>> List) {map<string, string> Map = (map<string, string>) ((hashmap<string, string>) List.get (0). Clone (); Map.put ("id","4"); }
Answer
- 2
- 2, 2, 3
- 2
Reason
List as an entry, is actually a reference to pass. That reference is also modified in the entry method.
There are two ways to solve this problem. one is to use clone, and the other is a new object 1. The modified list is then returned as an argument return, so that the entry is not affected.
It is important to note that both the list and the map are interfaces and there is no clone. ArrayList and HashMap have clone, and a shallow copy, not a deep copy of 2.
PS: I used to know the map, and now I don't remember anything. Two years not how to write Java, even & and && to use which do not know:
Never be too far from the code. Otherwise, you are far from the technology.
Reprint please indicate the source:
This article is from: "Ouyida3 's Blog"
2015.7.12
- Value and Address reference:
Http://www.blogjava.net/junglesong/archive/2008/02/22/181246.html?
- Deep copy and shallow copy online a lot of information:
Http://www.cnblogs.com/yxnchinahlj/archive/2010/09/20/1831615.html?
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
List and map of Java as a participant in clone