代码如下:
package com.wangzhu.arrays; import java.util.Arrays; import java.util.Collections; public class ArraysDemo { /** * @param args */ public static void main(String[] args) { Dog[] dogs = new Dog[] { new Dog(5), new Dog(2), new Dog(19), new Dog(21), new Dog(12), new Dog(1) }; printObject(dogs); // Arrays.sort(dogs); Collections.sort(Arrays.asList(dogs)); printObject(dogs); Cat[] cats = new Cat[] { new Cat(10), new Cat(0), new Cat(4), new Cat(5), new Cat(3) }; printObject(cats); // Arrays.sort(cats); Collections.sort(Arrays.asList(cats)); printObject(cats); } public static void printObject(Animal[] animals) { for (Animal animal : animals) { System.out.print("size = " + animal.getClass().getSimpleName() + animal.size + " "); } System.out.println(); } } class Animal implements Comparable<Animal> { int size; @Override public int compareTo(Animal animal) { return this.size - animal.size; } } class Dog extends Animal { public Dog(int size) { this.size = size; } } class Cat extends Animal { public Cat(int size) { this.size = size; } }