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.