Sorting an Array
1. 数字排序 int[] intArray = new int[] { 4, 1, 3, -23 };
Arrays.sort(intArray);
输出: [-23, 1, 3, 4]
2. 字符串排序,先大写后小写 String[] strArray = new String[]{ "z", "a", "C" };
Arrays.sort(strArray);
输出: [C, a, z]
3. 严格按字母表顺序排序,也就是忽略大小写排序 Case-insensitive sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
输出: [a, C, z]
4. 反向排序, Reverse-order sort
Arrays.sort(strArray, Collections.reverseOrder());
输出:[z, a, C]
5. 忽略大小写反向排序 Case-insensitive reverse-order sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(Arrays.asList(strArray));
输出: [z, C, a]
对于整数、字符串排序,jdk提供了默认的实现,如果要对一个对象数组排序,则要自己实现java.util.Comparator接口。
示例:
运行结果:
1. 数字排序 int[] intArray = new int[] { 4, 1, 3, -23 };
Arrays.sort(intArray);
输出: [-23, 1, 3, 4]
2. 字符串排序,先大写后小写 String[] strArray = new String[]{ "z", "a", "C" };
Arrays.sort(strArray);
输出: [C, a, z]
3. 严格按字母表顺序排序,也就是忽略大小写排序 Case-insensitive sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
输出: [a, C, z]
4. 反向排序, Reverse-order sort
Arrays.sort(strArray, Collections.reverseOrder());
输出:[z, a, C]
5. 忽略大小写反向排序 Case-insensitive reverse-order sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(Arrays.asList(strArray));
输出: [z, C, a]
对于整数、字符串排序,jdk提供了默认的实现,如果要对一个对象数组排序,则要自己实现java.util.Comparator接口。
示例:
import java.util.Arrays; import java.util.Comparator; class Cat { private String name; private float weight; public Cat(String name, float weight) { setName(name); setWeight(weight); } public Cat() { } public String getName() { return name; } public float getWeight() { return weight; } public void setName(String name) { this.name = name; } public void setWeight(float weight) { this.weight = weight; } } //创建一个比较器 class ByWeightComparator implements Comparator { public final int compare(Object c1, Object c2) { if(((Cat)c1).getWeight() > ((Cat)c2).getWeight()) { return 1; } else if(((Cat)c1).getWeight() == ((Cat)c2).getWeight()) { return 0; } else return -1; } } public class CatArrSortTest { public static void main(String[] args) { Cat c1 = new Cat("w", 100); Cat c2 = new Cat("d", 50); Cat c3 = new Cat("a", 80); Cat[] c = new Cat[]{c1, c2, c3}; System.out.println("排序前:"); for( Cat c4 : c) { System.out.print(c4.getName() + "," + c4.getWeight() + "\t"); } Arrays.sort(c, new ByWeightComparator()); System.out.println("\n排序后:"); for( Cat c4 : c) { System.out.print(c4.getName() + "," + c4.getWeight() + "\t"); } } }
运行结果: