首页 > 解决方案 > 在 Java 中创建列表列表时出现意外输出

问题描述

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 也会发生变化

标签: javaarraylist

解决方案


因为您将缓存数组 (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;

}

推荐阅读