1

Есть TreeSetсостоящий из объектов класса User как получить первый элемент коллекции? В классе User нет геттеров и сеттеров. Код User:

class User {
String name;
int age;

User(String n, int a) {
    name = n;
    age = a;
}

}

Код Main:

    class Main {
    public static void main(String[] args) {
         TreeSet<User> tree = new TreeSet<>(new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return o1.age - o2.age;
            }
        });
        tree.add(new User("Ivanov Ivan",30));
tree.add(new User("Stasov Stanislav",16));
    }
}

User и Main находятся в одном пакете

1 ответ 1

2

С помощью метода first, вот так:

User firstUser = tree.first();

Официальная документация TreeSet

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.