知识点:
- Arrays
Arrays.sort - 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);
}
}
}
例2:根据年龄对人进行排序
// 1. Person.java
package demo;
public class Person implements Comparable<Person>{
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);
}
}
}
例3:根据姓名对人进行排序
// 1. Person.java
package demo;
public class Person implements Comparable<Person>{
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
// 同上