java - 在 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 也会发生变化
解决方案
因为您将缓存数组 (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;
}
推荐阅读
- javascript - 为什么axios拦截器中不能设置cookies
- c# - 如果单击图像或文本,则仅单击自定义选项卡项
- php - 使用 guzzle 的多 CURL
- pdf - 如何运行 imagemagick 仅将多个 PDF 文件的第一页批量转换为 JPEG?
- reactjs - 仅在第二次执行时反应更新状态
- powershell - 无法在 powershell 的 try/catch 语句中捕获异常
- go - 如何使用接口和反射定义安全划分?
- c# - UWP 滑块 滑动后
- bash - Escape characters in AWK script within bash script
- django - Difference between my droplet's postgres database and a newly created managed database