java - 如何在 Java 中正确嵌套多个 ArrayLists/Maps?

标签 java dictionary arraylist nested

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

我正在从事一个项目,该项目要求我将多项式存储到 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>>

那么我该怎么做呢,还是我只是以错误的方式去做这件事?

最佳答案

你不能实例化new Map<String, Map<Integer, Integer>>()因为 java.util.Map 是一个接口(interface)(它没有构造函数)。您需要使用像 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<>();

关于java - 如何在 Java 中正确嵌套多个 ArrayLists/Maps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17586113/

相关文章:

python - 如何读取字典树

Python列表中的列表操作

Java Servlet 编程

java - 将新/自定义属性添加到 AEM 6.2 中的工作流收件箱

string - 从 map 获取值时出现意外值

java - HashMap 包含某个键,但告诉我它没有

java - 无法将字符添加到字符数组列表

java - Android 在 webview 上进行地理定位

java - 获取 Class<T> 的实例 [Runtime-Type Token]

ios - MapBox:如何删除一个形状并绘制另一个形状?