java系列21:数组的排序

知识点:

  1. Arrays
    Arrays.sort
  2. Comparable

例1:

package demo;

import java.util.Arrays;
import java.util.Iterator;

public class Test {
    public static void main(String[] args) {
        int[] array = {4, 5, 2, 1, 3};
        Arrays.sort(array);
        for (int i : array) {
            System.out.println(i);
        }
    }
}
java系列21:数组的排序_第1张图片
运行结果

例2:根据年龄对人进行排序

// 1. Person.java

package demo;

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

    public Person() {
    }

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

    @Override
    public String toString() {
        return "我的名字:" + name + ",我的年龄:" + age;
    }

    /**
     * 根据年龄进行排序
     */
    @Override
    public int compareTo(Person o) {
        int num = 0;
        if(this.age > o.age) {
            num = 1;
        } else if(this.age < o.age) {
            num = -1;
        } else {
            num = 0;
        }
        return num;
    }
}

// 2. Test1.java

package demo;

import java.util.Arrays;

public class Test1 {
    public static void main(String[] args) {
        Person[] persons = {new Person("lixingzhi", 25),
                new Person("Eva", 24),
                new Person("Neo", 18),
                new Person("Tom", 32),
                new Person("xiaofei", 12)
        };
        Arrays.sort(persons);
        for (Person person : persons) {
            System.out.println(person);
        }
    }
}
java系列21:数组的排序_第2张图片
运行结果

例3:根据姓名对人进行排序

// 1. Person.java

package demo;

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

    public Person() {
    }

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

    @Override
    public String toString() {
        return "我的名字:" + name + ",我的年龄:" + age;
    }

    /**
     * 根据年龄进行排序
     */
    @Override
    public int compareTo(Person o) {
        return this.name.compareTo(o.name);
    }
}

// 2. Test1.java
// 同上
java系列21:数组的排序_第3张图片
运行结果

你可能感兴趣的:(java系列21:数组的排序)