简体   繁体   English

地图的内存分配 <String,List<String> &gt;

[英]Memory assignement for Map<String,List<String>>

When we do Map<String,List<String>> = new HashMap<String, List<String>>(); 当我们做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? 它会创建一个空的地图,但地图内的List是否也为空或为空值?

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); 与ArrayList不同的是,它们是使用初始容量 (默认为10)创建的; meaning that creating an ArrayList<String> will allocate for an array of strings ( String[10] in that sense). 这意味着创建ArrayList<String>将分配一个字符串数组(在这种情况下为String[10] )。 So, HashMap<String, List<String>> is "cheaper" than List<Map<Whatever, NotOfInterest>> . 因此, HashMap<String, List<String>>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. 除非您从事“嵌入式计算”工作(或者一直在处理数百万个对象),否则您应该更加担心良好的OO设计,而不是Java集合的内存(或性能)成本。

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. 仅与参数化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> . 您正在使用泛型来强制使用泛型类型,泛型类型指出键的TYPE必须为String,而TYPE值必须为List<String> There is no List<String> in memory until you begin adding separately created List<String> objects into to your map. 在您开始将单独创建的List<String>对象添加到地图之前,内存中没有List<String> 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. 您可以继续从此处继续向地图添加更多列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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