我有一个有趣的问题,关于如何将任何数字插入有序的 ArrayList。假设用户输入 [12,34,37,60,89]
; addListElement()
方法应该遍历数组以找到新元素所在的索引。
用户输入数字50,新数组应该是[12,34,37,50,60,89]
。我使用for循环遍历ArrayList,但我不确定我的if()语句。
public void addListElement() {
System.out.println("Add number to arrayList");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int loc = 0;
for (int i = 0; i < aryList.size(); i++) {
if (number > 0 && i < loc) {
loc++;
}
}
aryList.add(loc, number);
System.out.println(aryList.toString());
}
最佳答案
试试这个:
int position = Collections.binarySearch(aryList, number);
aryList.add(position < 0 ? -position - 1 : position, number);
编辑感谢您指出如果数字已经存在,旧代码会崩溃
关于java - 将数字插入有序arrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12886762/