Collections

1.

package collections_method;

import java.util.Objects;

public class Person implements Comparable<Person>{
    private String name;
    private int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person() {
    }

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






    @Override
    public int compareTo(Person p) {
        return this.getAge()-p.getAge();
    }
}

2.

package collections_method;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class demo {
    public static void main(String[]args){
        ArrayList<Person> arr=new ArrayList<>();
        arr.add(new Person("aAlex",18));
        arr.add(new Person("bAlex",18));
        arr.add(new Person("Jeff",20));
        arr.add(new Person("Mike",17));
        Collections.sort(arr, new Comparator<Person>() {
                    @Override
                    public int compare(Person o1, Person o2) {
                        int result = o1.getAge() - o2.getAge();
                        if (result == 0) {
                            result = o1.getName().charAt(0) - o1.getName().charAt(0);
                        }
                        return result;
                    }
                });


        System.out.println(arr);
    }
}

ret:

[Person{name='Mike', age=17}, Person{name='aAlex', age=18}, Person{name='bAlex', age=18}, Person{name='Jeff', age=20}]

posted @ 2020-06-09 00:04  huxiaojie  阅读(96)  评论(0编辑  收藏  举报