一、数组
1.升序:Arrays.sort(arr);
2.降序:
方法一:Arrays.sort(arr,Collections.reverseOrder());
方法二:
package com.yh.sort; import java.util.Arrays; import java.util.Comparator; public class SortOverride { public static void main(String[] args) { // TODO Auto-generated method stub Integer[] arr = { 4, 6, 3, 9, 1, 5, 8 }; Comparator<Integer> c = new Mycomparator(); // 实例化一个Comparator对象 Arrays.sort(arr, c); for (Integer ele : arr) { System.out.print(ele + " "); } } } class Mycomparator implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { if(o1 > o2) return -1; if(o1 < o2) return 1; return 0; } }
二、ArrayList
1.升序:Collections.sort(arr);
2.降序:Collections.sort(arr,Collections.reverseOrder());
注:reverse()是倒序
String str = "qwewq";
String str1 =new StringBuilder(str).reverse().toString();