非常简单的例子,但是特别常用,可以引申出很多东西
- import java.util.Arrays;
- import java.util.Comparator;
- class Cat{
- Cat(int weight, int size){
- this.weight = weight;
- this.size = size;
- }
-
- @Override
- public String toString() {
- StringBuffer sBuffer = new StringBuffer();
- sBuffer.append("Cat[size:");
- sBuffer.append(size);
- sBuffer.append(",weight:");
- sBuffer.append(weight);
- sBuffer.append("] ");
- return sBuffer.toString();
- }
-
- int weight;
- int size;
- }
- class CatSizeComparactor implements Comparator<Cat>{
- @Override
- public int compare(Cat c1, Cat c2) {
- return c1.size - c2.size;
- }
- }
- class CatWeightComparactor implements Comparator<Cat>{
- @Override
- public int compare(Cat c1, Cat c2) {
- return c1.weight - c2.weight;
- }
- }
- public class ArraySortDemo {
- public static void main(String[] args) {
- Cat[] cats = {
- new Cat(50, 20),
- new Cat(27, 25),
- new Cat(61, 33),
- new Cat(55, 26),
- new Cat(24, 19),
- };
-
- System.out.println(Arrays.asList(cats));
- Arrays.sort(cats, new CatSizeComparactor());
- System.out.println(Arrays.asList(cats));
- Arrays.sort(cats, new CatWeightComparactor());
- System.out.println(Arrays.asList(cats));
- }
- }
复制代码
|
|