I have an ArrayList of multiple instances of the class ElementClass. Inside the ElementClass is a method named getCounter() that returns the value of the variable counter inside that class. This variable can only have 0, 1, or 2 as its values.
I need to sort these ArrayList entries in ascending order depending on the value that the method getCounter() returns. How can I accomplish that? I tried to research several methods but all those that I have found requires setting a value. For example:
list[i + 1] = temp
But ArrayLists do not allow setting a value. For example:
ArrayList<ElementClass> temp = list.get(i);
list.get(i + 1) = temp;
The above code would not allow me to compile because of errors. ArrayLists only allow adding of items at the end of the list (through the .add(item) method) and removing an item from a specific index (through the .remove(index) method.)
How can I accomplish the sorting using only the add() and remove() methods? Or is there another way to sort ArrayLists in Java?
1 Answer