Different Ways of Creating HashMaps

前端 未结 4 1390
盖世英雄少女心
盖世英雄少女心 2021-01-04 03:29

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          


        
相关标签:
4条回答
  • 2021-01-04 03:37

    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, i.e. once the application is running, the JVM will allow you to use any types for the keys and values.

    0 讨论(0)
  • 2021-01-04 03:38

    - 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();

    0 讨论(0)
  • 2021-01-04 03:40

    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>();
    
    0 讨论(0)
  • 2021-01-04 03:59

    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();
    
    0 讨论(0)
提交回复
热议问题