简体   繁体   中英

Java collections and memory use

I have a question on Java memory use. It's for my edification and anyone else who searches and finds this later! For the purpose of the question, please assume, this is a single method and nothing goes out of scope... during my question ;-)

I have created 5 new objects with a single property called 'name' of type String. I create an ArrayList and add the 5 objects to the ArrayList. I then create a HashMap and iterate through the previously created ArrayList, adding the objects to the HashMap.

Q1. When I add the objects from the ArrayList, to the HashMap, I assume I am just creating another collection of 'pointers', since I'm not using the 'new' keyword. Therefore no new memory is consumed, except for the HashMap itself (the objects are not duplicated).

Q2. If I change the value of 'name', in an object in the HashMap, would the same change be seen, if I were to iterate over the ArrayList, after making the change.

I appreciate a 'sanity check' on my understanding.

Q1: The HashMap is created and the references to the objects are created. So memory is consumed, but references aren't terribly big, but can make a difference if the number of references is huge.

Q2: Edit: Yes, the name field would change. Better still, write a small program to check it out.

A1 : Yes, other than the references and HashMap, nothing new will be created. (Assuming you are not creating a new set of keys for for the HashMap)

A2 : Yes, the change will reflect on the ArrayList.

To answer your questions.

1.) When you add objects to a HashMap the objects are not duplicated. Internally though the map will create new objects to maintain its inner structure. The inner structure of a map consists of HashMap.Entry objects that contain a linked list with all values that map to the same hash code. Thus whenever you add objects to a map one or more internal objects are created.

2.) I assume you stored the objects in the HashMap using their name as key. In this case chaning the name of an object will update the object (no matter whether it's being accessed through the list or the map, it's always the same object) but not the mapping in the map. In the map the object will still be store under its old name!

 Map map = new HashMap();
 Foo f = new Foo();
 f.setName("A");
 map.put(f.getName(),f);
 f.getName(); // => "A"
 map.get("A"); // => f
 f.setName("B");
 f.getName(); // => "B"
 map.get("B"); // => null
 map.get("A"); // => f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM