调用java类排序有三种情况:(这里都以int排序)
<1>:直接对数组排序:
import java.util.Arrays; public class SortArray { public static void main(String[] args) { int []arr1 = {1,9,6,2,7,5,4,8,3}; int []arr2 = {1,9,6,2,7,5,4,8,3}; sort(arr1); sort(arr2,0,5); } //按升序对数组中的[fromIndex,toIndex)进行排序(即从fromIndex--(toIndex-1)的数据) public static void sort(int[] arr,int fromIndex,int toIndex){ Arrays.sort(arr, fromIndex, toIndex); System.out.println("Arrays.sort(arr, 0, 5):"); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println(); } //按升序对数组全部数据排序 public static void sort(int[] arr){ Arrays.sort(arr); System.out.println("Arrays.sort(arr):"); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println(); } }
<2>:对List进行排序 本身实现Comparable接口
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CollectionsOfSort { public static void main(String[] args) { List<Stu> list = new ArrayList<Stu>(); list.add(new Stu(1)); list.add(new Stu(9)); list.add(new Stu(6)); list.add(new Stu(2)); list.add(new Stu(7)); sort(list); } public static void sort(List<Stu> list) { Collections.sort(list); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).id + " "); } } } class Stu implements Comparable<Stu> { Integer id; public Stu(int id) { this.id = id; } @Override public int compareTo(Stu stu) { return this.id.compareTo(stu.id); // return stu.id.compareTo(this.id);//降序排列 } }
<3>:对List进行排序 另写程序实现Comparator 接口
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class CollectionsOfSort { public static void main(String[] args) { List<Person> listPerson =new ArrayList<Person>(); listPerson.add(new Person(1)); listPerson.add(new Person(9)); listPerson.add(new Person(6)); listPerson.add(new Person(2)); listPerson.add(new Person(7)); sort(listPerson, new SortPerson()); } public static void sort(List<Person> list, Comparator<Person> c) { Collections.sort(list, c); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i).age + " "); } } } class SortPerson implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p1.age.compareTo(p2.age); // return p2.age.compareTo(p2.age);//降序 } } class Person { public Person(int age) { this.age = age; } Integer age; }