代码如下:

 

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;
    }
}

 

相关文章:

  • 2021-09-17
  • 2022-01-24
  • 2021-08-06
  • 2021-10-11
  • 2021-06-14
  • 2022-12-23
  • 2021-07-04
  • 2021-05-31
猜你喜欢
  • 2021-10-24
  • 2021-09-14
  • 2021-05-07
  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
相关资源
相似解决方案