How does one instantiate an array of maps in Java?

后端 未结 8 1254
刺人心
刺人心 2020-11-30 06:34

I can declare an array of maps using generics to specify the map type:

private Map[] myMaps;

However, I can\'t figur

8条回答
  •  鱼传尺愫
    2020-11-30 07:14

    Not strictly an answer to your question, but have you considered using a List instead?

    List> maps = new ArrayList>();
    ...
    maps.add(new HashMap());
    

    seems to work just fine.

    See Java theory and practice: Generics gotchas for a detailed explanation of why mixing arrays with generics is discouraged.

    Update:

    As mentioned by Drew in the comments, it might be even better to use the Collection interface instead of List. This might come in handy if you ever need to change to a Set, or one of the other subinterfaces of Collection. Example code:

    Collection> maps = new HashSet>();
    ...
    maps.add(new HashMap());
    

    From this starting point, you'd only need to change HashSet to ArrayList, PriorityQueue, or any other class that implements Collection.

提交回复
热议问题