sort
static void sort(int[] a) :将a数组按照从小到大进行排序
static void sort(int[] a, int fromIndex, int toIndex) :将a数组的[fromIndex, toIndex)部分按照升序排列
static void sort(Object[] a) :根据元素的自然顺序对指定对象数组按升序进行排序。
static <T> void sort(T[] a, Comparator<? super T> c) :根据指定比较器产生的顺序对指定对象数组进行排序。
需要自己定义比较器
import org.junit.Test;
import java.text.Collator;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
public class TestArrays {
@Test
public void test02() {
int[] arr = {3, 2, 5, 1, 6};
System.out.println("排序前" + Arrays.toString(arr));
Arrays.sort(arr);
System.out.println("排序后" + Arrays.toString(arr));
Student[] students = new Student[3];
students[0] = new Student("张三", 96);
students[1] = new Student("李四", 85);
students[2] = new Student("王五", 98);
System.out.println(Arrays.toString(students));
Arrays.sort(students);
System.out.println(Arrays.toString(students));
Arrays.sort(students, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return Collator.getInstance(Locale.CHINA).compare(((Student) o1).getName(), ((Student) o2).getName());
}
});
System.out.println(Arrays.toString(students));
}
}
class Student implements Comparable {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
@Override
public int compareTo(Object o) {
return this.score - ((Student)o).score;
}
}
标签:常用,java,数组,int,Arrays,score,Student,public,name
From: https://www.cnblogs.com/abc-begin/p/17539509.html