简体   繁体   中英

Memory assignement for Map<String,List<String>>

When we do Map<String,List<String>> = new HashMap<String, List<String>>(); it creates an empty map but is the List inside the map empty as well or is it a null value?

To a certain degree, this depends on the collection type you are using. A hashmap or hashset will not allocate any space for objects that will potentially be added later on. So you only carry the "cost" for exactly that one map or set object when creating it.

Whereas for ArrayList, that is different - they are created using an initial capacity (10 by default); meaning that creating an ArrayList<String> will allocate for an array of strings ( String[10] in that sense). So, HashMap<String, List<String>> is "cheaper" than List<Map<Whatever, NotOfInterest>> .

On the other hand: this is really not something to worry about. Unless you are working in "embedded computing" (or you are dealing with millions of objects all the time), you should much more worry about good OO designs instead of memory (or performance) cost of java collections.

Accepted answer: When you instantiate a collection, it is empty. Any initial capacity it has are of null values, so there are no Lists in this case. – Zircon

Your code:

Map<String,List<String>> = new HashMap<String, List<String>>();

pertains only to the instantiation of a parameterized HashMap. You are using generics to enforce generic types, which states that the TYPE for key must be a String and the TYPE value must be a List<String> . There is no List<String> in memory until you begin adding separately created List<String> objects into to your map. This would look like this:

Map<String, List<String>> myMap = new HashMap<>();//BTW, You only need to parameterize the object declaration since Java 7

List<String> names = new ArrayList<String>();
names.add("Betty");
names.add("Bob");
names.add("Jessica");
names.add("Jim");
myMap.put("names", names);//Where "names" is your key and names is your value.

You can proceed to continue adding more lists to your map from there.

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