问题
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