如何创建二维 ArrayList 并添加元素

How to create 2D ArrayList and add elements

我有一个小程序,可以在二维数组中保存成对的州及其首都。本节目下方:

public class StateCapitals {

public static void main(String[] args) {
    String[][] answers = {
            {"Alabama", "Montgomery"},
            {"Alaska", "Juneau"},
            {"Arizona", "Phoenix"},
            {"Arkansas", "Little Rock"},
            {"California", "Sacramento"},
            {"Colorado", "Denver"},
            {"Connecticut", "Hartford"},
            {"Delaware", "Dover"},
            {"Florida", "Tallahassee"},
            {"Georgia", "Atlanta"}
    };


    int correctCount = 0;

    for (int i = 0; i < answers.length; i++) {


        System.out.print("What is the capital of " + answers[i][0]);

        Scanner input = new Scanner(System.in);

        String userInput = input.nextLine();



        for (int j = 0; j < answers[i].length - 1; j++) {
            System.out.println("The correct answer should be " + answers[i][j + 1]);

            if(userInput.equals(answers[i][j + 1]))
                correctCount++;

        }


    }

    System.out.println("The correct count is " + correctCount);
    }
}

我需要用 List<List<String>> super2dArray = new ArrayList<ArrayList<String>>() 替换常规二维数组。

我在 Whosebug 上找到了一些线程如何添加我想要的数组。这是链接:How to create an 2D ArrayList in java? andHow do I declare a 2D String arraylist?。但是这些讨论并没有解释如何在每个 ArrayList 中添加元素。我能做的最好的事情是创建新的 ArrayList,然后添加一些元素,最后将 ArrayList 附加到另一个元素。他们没有解释如何向 2D ArrayList 添加元素。

这里有一个更简单的例子:)

请注意,我为 ArrayList 的构造函数提供了固定的初始长度,因为我们已经知道数组的长度。

List<List<String>> myListOfListOfString = new ArrayList<List<String>>(answers.length);

for(String[] array : answers)
    myListOfListOfString.add(Arrays.asList(array));

有关详细信息,请参阅文档。