java - 向数组列表添加值执行不会停止
问题描述
我想构建一个考虑整数列表的算法,对其进行排序。
这个想法是:遍历整数列表,第一个值进入一个新列表;以下值与新列表中唯一存在的值进行比较,并将其放在之前或之后,依此类推。
import java.util.*;
import java.util.function.Supplier;
import java.util.ArrayList;
public class SortLists {
public static void main(String args[])
{
// list [5,1,4,2,8]
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(1);
list.add(4);
list.add(2);
list.add(8);
System.out.println("list : " + list.toString());
// new empty list
List<Integer> list2 = new ArrayList<Integer>();
// iterate over the integer list
for (int i = 0; i < list.size(); i++){
//int i=2;
// *** 1st iteration - add the value to the list2
if (i == 0){
list2.add(list.get(i));
} else {
// *** in the next interations, compare with the existing values in list2
for (int j = 0; j < list2.size(); j++){
// *** Note: this if is unecessary but I got an error with list2.get(j)
if (j==0){
// if the value from list is lower than the only value in list2, put in index 0
if (list.get(i) < list2.get(0) ) {
list2.add(j,list.get(i));
}
}else{
if (list.get(i) < list2.get(j) ) {
//list2.add(j,list.get(i)); // GIVES ERROR!
System.out.println("index "+j+" value "+list.get(i));
} else {
//list2.add(list.get(i)); //GIVES ERROR!
System.out.println("else: index "+j+" value "+list.get(i));
}
}
}
}
}
//list2.add(1,4); // no error if add manually here
System.out.println("list2 : " + list2.toString());
}
}
5 和 1 正确插入到 list2 中。
另外两个list2.add
,如果我取消注释它们,执行不会停止。
解决方案
执行不会停止
您进入了一个无限循环,因为在内部for
循环中,您在迭代列表时将元素添加到第二个列表。
此外,您不必要地使事情复杂化。只需存储第一个list.get(i) < list2.get(j)
为 true 的索引。如果存在这样的索引,则将列表一中的第 i 个元素添加到该索引处的列表二。否则,将列表一中的第 i 个元素添加到列表二的末尾。
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(5);
list.add(1);
list.add(4);
list.add(2);
list.add(8);
System.out.println("list : " + list.toString());
List<Integer> list2 = new ArrayList<Integer>();
list2.add(list.get(0));
for (int i = 1; i < list.size(); i++){
int index = list2.size();
for(int j = 0; j < list2.size(); j++){
if (list.get(i) < list2.get(j)){
index = j;
break;
}
}
list2.add(index,list.get(i));
}
System.out.println(list);
System.out.println(list2);
}
推荐阅读
- dialogflow-es - webhook 请求超时 dialogflow v2 迁移(webhook 代码:4)?
- .net - 如何使用经典的 VS csproj 定位 .NET Core?
- java - Delphi 10.2 TNetHTTPClient 在其时间之前超时
- regex - 如何在正则表达式中排除非数字字符
- ios - xcode 10.2 中的 Simulator 3d Touch 选项不可用
- node.js - 从节点 js 查询时无法从 AS400 DB2 数据库中获取 *loval 值
- sql - 使用合并时排序
- python - 如何在 django admin 中添加脚本 type="module"
- firebase - Cloud Firestore for Spark 计划中允许的同时连接是什么
- c++ - 强制访问私有成员