0
点赞
收藏
分享

微信扫一扫

【java】LinkedList 和 ArrayList的简介与对比

胡桑_b06e 2023-08-31 阅读 40

示例代码:

import java.util.*;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Alice", 25));
        personList.add(new Person("Bob", 30));
        personList.add(new Person("Charlie", 28));

        // 使用比较器来比较年龄属性
        Comparator<Person> ageComparator = Comparator.comparingInt(Person::getAge);

        // 找到年龄最大的人
        Person oldestPerson = Collections.max(personList, ageComparator);

        System.out.println("Name: " + oldestPerson.getName() + ", Age: " + oldestPerson.getAge());
    }
}

在这个例子中,ageComparator 使用 Comparator.comparingInt() 方法来创建一个比较器,以便根据年龄属性进行比较。然后,Collections.max() 方法使用这个比较器来找到年龄属性最大的那个 Person 对象。

举报

相关推荐

0 条评论