簡體   English   中英

如何創建2D ArrayList並添加元素

[英]How to create 2D ArrayList and add elements

我有一個小程序,在2D數組中保存成對的狀態和它們的大寫字母。 在這個程序下面:

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>>()替換常規2D數組。

我在stackoverflow上發現了一些線程如何添加我想要的數組。 這是鏈接: 如何在java中創建2D ArrayList? 以及如何聲明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));

有關詳細信息,請參閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM