如何在不使用 Java 集合的情况下对数组列表进行排序 [英] How to do sorting in array list without using collections in Java
问题描述
ArrayList <整数>数组列表 = 新数组列表 <整数>();数组列表.添加(10010);arraylist.add(5);arraylist.add(4);arraylist.add(2);for (int i = 0; i < arraylist.size(); i++) {for (int j = arraylist.size() - 1; j > i; j--) {if (arraylist.get(i) > arraylist.get(j)) {int tmp = arraylist.get(i);arraylist.get(i) = arraylist.get(i);arraylist.get(j) = tmp;}}}for (int i: arraylist) {System.out.println(i);}
交换时出错,LHS 应该是可变的.我明白了.Set 方法在这里有效,但我不想使用.有没有办法在不使用 set 方法的情况下做到这一点?非常感谢您的帮助.
arraylist.get(i)= arraylist.get(i);arraylist.get(j) =tmp;
您不能为方法调用赋值.正如编译器告诉你的,赋值的左边必须是一个变量.
使用set
方法:
arraylist.set(i,arraylist.get(j));arraylist.set(j,tmp);
<块引用>
有没有不使用 set 方法的方法?
没有.除非您希望将 ArrayList 转换为数组,否则请对数组进行排序,然后使用排序后的数组更新 ArrayList.
ArrayList < Integer > arraylist = new ArrayList < Integer > ();
arraylist.add(10010);
arraylist.add(5);
arraylist.add(4);
arraylist.add(2);
for (int i = 0; i < arraylist.size(); i++) {
for (int j = arraylist.size() - 1; j > i; j--) {
if (arraylist.get(i) > arraylist.get(j)) {
int tmp = arraylist.get(i);
arraylist.get(i) = arraylist.get(i);
arraylist.get(j) = tmp;
}
}
}
for (int i: arraylist) {
System.out.println(i);
}
It is giving error while swapping, The LHS should be variable. I understand it. Set method works here but I do not want to use. Is there a way to do it without using set method? Help is really appreciated.
arraylist.get(i)= arraylist.get(i);
arraylist.get(j) =tmp;
You can't assign a value to a method call. As the compiler told you, the left hand side of an assignment must be a variable.
Use set
method :
arraylist.set(i,arraylist.get(j));
arraylist.set(j,tmp);
Is there a way to do it without using set method?
No. Unless you wish to convert your ArrayList to an array, sort the array, and update the ArrayList with the sorted array.
这篇关于如何在不使用 Java 集合的情况下对数组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!