【问题标题】:How do you properly nest multiple ArrayLists / Maps in Java?如何在 Java 中正确嵌套多个 ArrayLists / Maps?
【发布时间】:2013-07-09 07:06:24
【问题描述】:

我正在尝试运行一个非常简单的程序,但我停留在声明嵌套列表和映射的基础知识上。

我正在做一个需要我将多项式存储到 ArrayList 中的项目。 每个多项式都被命名,所以我想要一个键/值映射来拉取多项式的名称(1、2、3 等)作为键,并将实际的多项式作为值。

现在实际的多项式也需要键值,因为该程序的性质要求指数与系数相关联。

例如,我需要一个多项式的 ArrayList,假设第一个很简单:

多项式 1:2x^3

数组列表包含整个事物作为映射,映射包含键:多项式 1 和值:是映射...其中 2 和 3 是键/值。

我的代码如下,但我不是 100% 了解如何格式化这种嵌套逻辑。

public static void main(String[] args) throws IOException{
        ArrayList<Map> polynomialArray = new ArrayList<Map>();
        Map<String, Map<Integer, Integer>> polynomialIndex = new Map<String, Map<Integer, Integer>>();
        String filename = "polynomials.txt";
        Scanner file = new Scanner(new File(filename));

        for(int i = 0; file.hasNextLine(); i++){
            //this will eventually scan polynomials out of a file and do stuff

        }

编辑: 更新了 Map 中的键/值,还是有问题。

上面的代码给了我以下错误:

Cannot instantiate the type Map<String,Map<Integer,Integer>>

那么我该怎么做呢,还是我只是做错了?

【问题讨论】:

  • 您在寻找List&lt;Integer,Map&lt;Integer,Map&lt;Integer,Integer&gt;&gt; 吗?
  • 更像 ArrayList>> 原来的 ArrayList 不需要键/值
  • 那么就像ArrayList&lt;Map&lt;String, Map&lt;Integer,Integer&gt;&gt;&gt;,Map有一个键值对。
  • 你不能为你的多项式创建一个class,然后使用List&lt;Polynomial&gt; = new ArrayList&lt;&gt;吗?

标签: java map arraylist nested


【解决方案1】:

您不能实例化new Map&lt;String, Map&lt;Integer, Integer&gt;&gt;(),因为java.util.Map 是一个接口(它没有构造函数)。你需要使用像java.util.HashMap这样的具体类型:

Map<String, Map<Integer, Integer>> polynomialIndex = new HashMap<String, Map<Integer, Integer>>();

另外,如果您使用的是 Java 7 或更高版本,您可以使用 generic type inference 来节省一些输入:

Map<String, Map<Integer, Integer>> polynomialIndex = new HashMap<>();

【讨论】:

  • 是的,我刚刚意识到这一点。我从来没有完全确定这一切意味着什么,但现在我自己也遇到了这个问题,它开始变得更有意义了。
【解决方案2】:

这是不正确的:

Map<String, Map<Integer>> polynomialIndex = new Map<String, Map<Integer>>();

地图需要有两个参数,而您的嵌套地图Map&lt;Integer&gt; 只有一个。我认为您正在寻找类似的东西:

Map<String, Map<Integer, Integer>> polynomialIndex = new Map<String, Map<Integer, Integer>>();

或者最好分开做。

Map<String, Map> polynomialIndex = new Map<String, Map>();
Map<Integer, Integer> polynomialNumbers = new Map<Integer, Integer>();

有了这个,你可以把数字放在 polynomailNumbers 映射中,然后在 polynomialIndex 中使用。

【讨论】:

  • 我也试过了,但它给出了错误:无法实例化类型 Map>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2016-02-14
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多