簡體   English   中英

創建ArrayList <Integer>的ArrayList

[英]Create an ArrayList of ArrayList<Integer>

我正在嘗試使用下面的代碼來創建一個多維ArrayList。 我的代碼填充內部ArrayList(localSolutions)就好了,但是當我嘗試將ArrayList添加到外部ArrayList(解決方案)時,出現了問題,並且它添加了空ArrayLists。

public class MathCapstone {

public static void main(String[] args) {
    ArrayList<ArrayList<Integer>> list = entireList(10);

    for(int q = 0;q<list.size();q++) {
        System.out.println(list.get(q));
    }

public static ArrayList<ArrayList<Integer>> entireList(int max) {
    ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> localSolutions = new ArrayList<Integer>();

    for(int i = 1; i <= max; i++) {
        for(int j = 1; j < i; j++) {
           //System.out.println(j + "mod" + i + "=" + (j*j)%i);
            if ((j*j)%i == 1) {
                localSolutions.add(j);
            }
        }
        //System.out.println(localSolutions.toString());
        solutions.add(localSolutions);
        localSolutions.clear();
    }
    return solutions;
}

最后要說明的是:使用ArrayLists的HashMap會不會更好(最終我將創建最大值約為10k的CDF)?

您正在清除localSolutions列表。

在Java中,您只能通過值復制對Object的引用而不是實際對象本身。 因此,當您在解決方案列表中添加localSolutions列表時, localSolutions引用和解決方案列表的第一個條目都指向同一個對象。

因此,清除localSolutions列表時,可以有效清除解決方案列表中的第一個條目。

你在做:

localSolutions.clear();

將列表添加到另一個列表不會添加列表的副本,它會添加相同的列表對象。 您的代碼在外環中執行的操作是使用元素填充相同的列表,清空它並將其添加到solutions solutions包含對同一個空列表的max引用。

你想要做的是:

ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>();
for(int i = 1; i <= max; i++) {
    ArrayList<Integer> localSolutions = new ArrayList<Integer>();
    for(int j = 1; j < i; j++) {
       //System.out.println(j + "mod" + i + "=" + (j*j)%i);
        if ((j*j)%i == 1) {
            localSolutions.add(j);
        }
    }
    //System.out.println(localSolutions.toString());
    solutions.add(localSolutions);
}

暫無
暫無

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

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