Question: 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 `ArrayList`s 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. `ArrayList`s 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?

Answer: 
```
Collections.sort(list, new Comparator<ElementClass>() {
   public int compare(ElementClass a, ElementClass b){
      return a.getCounter()-b.getCounter();
   }
});

```
```
Collections.sort(list, new Comparator<ElementClass> {
    @Override
    public int compare(ElementClass o1, ElementClass o2) {
        if (o1.getCounter() == o2.getCounter()) {
            return 0;
        }
        return o1.getCounter() < o2.getCounter() ? -1 : 1;
    }
}

```

if `getCounter` uses wrapper class (like `Integer` instead of `int`), you can do:

```
Collections.sort(list, new Comparator<ElementClass> {
    @Override
    public int compare(ElementClass o1, ElementClass o2) {
        return (o1.getCounter().compareTo(o2.getCounter());
    }
}

```