Avatar ·

How to sort an ArrayList of custom objects by a property (field) in Java?

Hello everyone! I'm a beginner Java developer and I'm having trouble sorting a list of objects. I have a `User` class with fields `name` (String) and `age` (int). I create an `ArrayList`, add several users to it, and want to sort them by age (ascending). I tried using `Collections.sort(list)`, but the compiler complains that my `User` class does not implement the `Comparable` interface. Here's my code: ```java import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { ArrayList users = new ArrayList<>(); users.add(new User("Alice", 30)); users.add(new User("Bob", 25)); users.add(new User("Charlie", 35)); // Compilation error Co