有没有一种方法来实现LinkedHashMap的数组? [英] Is there a way to implement an array of LinkedHashMap?

查看:89
本文介绍了有没有一种方法来实现LinkedHashMap的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现LinkedHashMap的数组,但我不知道是否有可能...

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

目前,我的代码如下:

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

返回"NullPointerException" ...

returns a "NullPointerException"...

您知道如何实现吗?

1.擦除extract(),2.表格->数组

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

推荐答案

我不知道您的 extracted()方法正在尝试做什么.您将得到一个 NullPointerException ,因为您是将 map 传递到 extracted 中,然后立即将其返回.在您的示例中,您要传入 null ,然后将其返回.在空数组上找不到第i个 下标(或任何下标).

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.

List 可以代替 LinkedHashMap 的数组吗?

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

编辑

顺便说一句,您不能使用泛型实例化数组.如果您需要类型安全性,建议您与列表一起使用.否则,您必须解决以下问题:

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];

但是,这会给您警告.

这篇关于有没有一种方法来实现LinkedHashMap的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆