参考链接:数组排序
调用方法:(注意:默认升序排序)
int[]nums=new int[5]; nums[0] = -7; nums[1] = -3; nums[2] = 2; nums[3] = 3; nums[4] = 11;
Arrays.sort(nums); //data数组名
举例:
977.有序数组的平方
public static int[] sortedSquares(int[] nums) { int data[] = new int[nums.length]; /*开辟了一个长度为3的数组*/ // ArrayList<Integer>data=new ArrayList<>(); for (int i=0;i<nums.length;i++){ data[i]=nums[i]*nums[i]; } Arrays.sort(data); return data; }
调用方法:(注意:默认升序排序)
List<Integer> list = new ArrayList<Integer>(Arrays.asList(10, 3, 6, 1, 4, 5, 9)); Collections.sort(list);
调用方法:(注意:降序排序)
Comparator<Integer> reverseComparator = Collections.reverseOrder(); Collections.sort(list, reverseComparator);
重写compare方法 (注意:升序排序)
//年龄为null时为小
Student studentWang = new Student("王小二", 10); Student studentZhang = new Student("张三", 1); Student studentGou = new Student("狗子", 99); Student studentZhao = new Student("赵六", 40); Student studentLi = new Student("李四", null); List<Student> students = new ArrayList<Student>(Arrays.asList(studentWang, studentZhang, studentGou, studentZhao, studentLi)); Collections.sort(students, new Comparator<Student>() { public int compare(Student o1, Student o2) { if(null == o1.getAge()) { return -1; } if(null == o2.getAge()) { return 1; } return o1.getAge().compareTo(o2.getAge()); }
compare方法:
compareTo:
前两种for循环赋给一个新数组
第三种:重写compare方法 (注意:降序排序)
//年龄为null时为最大
Student studentWang = new Student("王小二", 10); Student studentZhang = new Student("张三", 1); Student studentGou = new Student("狗子", 99); Student studentZhao = new Student("赵六", 40); Student studentLi = new Student("李四", null); List<Student> students = new ArrayList<Student>(Arrays.asList(studentWang, studentZhang, studentGou, studentZhao, studentLi)); Collections.sort(students, new Comparator<Student>() { public int compare(Student o1, Student o2) { if(null == o1.getAge()) { return 1; } if(null == o2.getAge()) { return -1; } return o2.getAge().compareTo(o1.getAge()); }