【问题标题】:Unexpected output when creating a List of Lists in Java在 Java 中创建列表列表时出现意外输出
【发布时间】:2018-10-16 05:38:42
【问题描述】:
class Solution {
    public List<List<Integer>> largeGroupPositions(String S) {
        //int k=0;
        List<Integer> l1 = new ArrayList<Integer>();
        List<List<Integer>> l2 = new ArrayList<List<Integer>>();
        int n = S.length();

        int count =1, i1=0, i2=0;
        for(int i=1; i<n; i++){
            if(S.charAt(i)==S.charAt(i-1)){
                count++;

            }else{
                i2 = i-1;
                if(count>=3){
                    l1.add(i1);
                    l1.add(i2);
                    l2.add(l1);


                }

                count =1;
                i1=i;
            }
        }

        return l2;

    }
}

我需要这个输出[[3,5],[6,9],[12,14]],但我得到[[3,5,6,9,12,14],[3,5,6,9,12,14],[3,5,6,9,12,14]],如果我在其他部分使用 l1.clear(),那么 l2 也会发生变化

【问题讨论】:

标签: java arraylist


【解决方案1】:

您将所有整数添加到同一个内部列表(您在方法开头使用语句 List&lt;Integer&gt; l1 = new ArrayList&lt;Integer&gt;(); 创建的那个)。

您应该在向其添加元素之前创建一个新的List

for(int i=1; i<n; i++) {
    if(S.charAt(i)==S.charAt(i-1)) {
        count++;
    } else {
        i2 = i-1;
        if(count>=3) {
            List<Integer> l1 = new ArrayList<Integer>();
            l1.add(i1);
            l1.add(i2);
            l2.add(l1);
        }

        count =1;
        i1=i;
    }
}

【讨论】:

  • @risabh_95 实际上没有其他方法,因为您不能重用相同的列表实例。为什么你认为你不能创建这样的列表?
  • @risabh_95 你注意到我移动了List&lt;Integer&gt; l1 = new ArrayList&lt;Integer&gt;(); 语句吗? i can't create new list 是什么意思?
【解决方案2】:

因为您将缓存数组 (List l1 = new ArrayList();) 设为全局。

所以每次添加时,都会添加到同一个数组中。而且你不能只清除它,因为你将它添加到 l2,清除 l1 也会清除数组,就像它在 l2 中一样。

原因是当你将 l1 添加到 l2 时,它不会将 l1 的值复制到 l2 中,而是将 l1 的指针(或引用)添加到 l2 中。所以它实际上只有一个支持数组。

试试这样的:

class Solution {
public List<List<Integer>> largeGroupPositions(String S) {
//int k=0;

List<List<Integer>> l2 = new ArrayList<List<Integer>>();
int n = S.length();

int count =1, i1=0, i2=0;
for(int i=1; i<n; i++){
List<Integer> l1 = new ArrayList<Integer>();
    if(S.charAt(i)==S.charAt(i-1)){
        count++;

    }else{
        i2 = i-1;

        if(count>=3){
            List<Integer> l1 = new ArrayList<Integer>();
            l1.add(i1);
            l1.add(i2);
            l2.add(l1);


        }

        count =1;
        i1=i;
    }
}

return l2;

}

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 2015-10-21
    • 1970-01-01
    • 2023-04-01
    • 2022-11-28
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多