有没有办法实现LinkedHashMap的数组?
我正在尝试实现 LinkedHashMap 数组,但我不知道是否可能......
目前我的代码如下所示:
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"...您知道如何实施吗?
编辑:1.擦除提取(),2.表->数组
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道您的
extracted()
方法想要做什么。您收到NullPointerException
是因为您将map
传递到extracted
中,然后立即返回它。在您的示例中,您传入null
然后返回它。您无法在空数组上找到第 ith 下标(或任何下标)。List
可以代替LinkedHashMap
数组吗?编辑
顺便说一下,你不能用泛型实例化数组。如果您想要类型安全,我建议您使用该列表。否则你就不得不凑合:
但是,这会给你警告。
I don't know what your
extracted()
method is trying to do. You're getting aNullPointerException
because you're passingmap
intoextracted
and then you're returning it immediately. In your example, you're passing innull
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 aList
work?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:
This will give you warnings, however.
这将导致 NPE,因为您从不初始化映射,或者更确切地说,您显式地将其初始化为 NULL:
编辑:
您需要实例化数组,例如:
尽管您会收到该代码的“未经检查的转换”警告。另请检查此以了解通用数组创建问题(感谢那些指出它的人出去)。
That will cause an NPE because you never initialize map, or rather, you explicitly initialize it to NULL:
EDIT:
You need to instantiate the array, e.g.:
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).