简体   繁体   中英

Different Ways of Creating HashMaps

I've been learning about HashMaps recently but I have one question that I can't seem to get a clear answer on. The main difference between -

HashMap hash1 = new HashMap();

vs

HashMap<,>hash1 = new HashMap <,> (); //Filled in with whatever Key and Value you want. 

I thought when you define a HashMap it requires the Key and Value. Any help would be much appreciated. Thank You.

Those are the options you have:

J2SE <5.0 style:

 Map map = new HashMap();

J2SE 5.0+ style (use of generics ):

 Map<KeyType, ValueType> map = new HashMap<KeyType, ValueType>();

Google Guava style (shorter and more flexible):

 Map<KeyType, ValueType> map = Maps.newHashMap();

You should take a look on Java generics , if you don't specify the types of the HashMap, both key and value will be Object type.

So, if you want a HashMap with Integer keys and String values for instance:

    HashMap<Integer, String> hashMap= new HashMap<Integer, String>();

Specifying the key and the value types allows for greater type-safety by enabling compile-time typing enforcement.

This makes it easier to write code that doesn't accidentally mix up the key and value types, and reduces the amount of casts that you must explicitly declare in the code.

However, it is important to be aware the these type-checks are compile-time only, ie once the application is running, the JVM will allow you to use any types for the keys and values.

- Generics can be implied to classes, interfaces, methods, variables etc.. but the most important reason for which its used is making the Collection more type safe .

- Generics make sure that only specific type of object enters and comes out of the Collections .

- Moreover its worth mentioning that there is a process known as Erasure ,

-> Erasure is a process where the type parameters and type arguments are removed from the generic classes and interfaces by the compiler , making it back compatible with the codes that where written without Generics.

So,

HashMap<String, Integer> map = new HashMap<String, Integer>();

becomes of Raw type ,

HashMap map = new HashMap();

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