Is there a way to implement an array of LinkedHashMap?

感情迁移 提交于 2021-02-16 15:25:32

问题


I am trying to implement an array of LinkedHashMap but I don't know if it's possible...

For the moment my code looks like as follows :

public class LHMap {

    public static void main(String[] args) {

     LinkedHashMap<String, Integer>[] map = null;

  for (int i = 0; i < 5; i++) {
         map[i] = new LinkedHashMap<String, Integer>();
  }

  map[0].put("a", 0);
  System.out.println(map[0].get("a"));

 }
}


System.out.println(extracted(map)[0].get("a"));
returns a "NullPointerException"...

Have you got any idea how to implement this?

EDIT : 1. erase extracted(), 2. table->array


回答1:


I don't know what your extracted() method is trying to do. You're getting a NullPointerException because you're passing map into extracted and then you're returning it immediately. In your example, you're passing in null and then returning it. You can't find the ith subscript (or any subscript) on a null array.

Instead of an array of LinkedHashMap, would a List work?

List<Map<String, Integer>> listOfMaps = new ArrayList<Map<String, Integer>>();

for(int i = 0; i < 5; i++) {
   listOfMaps.add(new LinkedHashMap<String, Integer>());
}

listOfMaps.get(0).put("a", 0);
System.out.println(listOfMaps.get(0).get("a"));

EDIT

You cannot instantiate an array with generics, by the way. I'd suggest going with the list if you want the type-safety. Otherwise you'd have to make do with:

LinkedHashMap<String, Integer>[] map = new LinkedHashMap[5];

This will give you warnings, however.




回答2:


map[i] = new LinkedHashMap<String, Integer>();

That will cause an NPE because you never initialize map, or rather, you explicitly initialize it to NULL:

LinkedHashMap<String, Integer>[] map = null;

EDIT:

You need to instantiate the array, e.g.:

map = (LinkedHashMap<String, Integer>[]) new LinkedHashMap[5];

Although you'll get an "unchecked conversion" warning with that code. Also check this for the generic array creation issue (thanks for those who pointed it out).



来源:https://stackoverflow.com/questions/4128923/is-there-a-way-to-implement-an-array-of-linkedhashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!