Chapter 16 - Exercise 21

(3) Try to sort an array of the objects in Exercise 18. Implement Comparable to fix the problem. Now create a Comparator to sort the objects into reverse order.


Sphere.java



package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class Sphere{
    private static int count=0;
    private int id=++count;
    public String toString(){return "Sphere "+id;}
    public void setId(int inNum){id=inNum;}
    public int getId(){return id;}
}


SphereComparator.java



package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class SphereComparator implements Comparator<Sphere>{
    
    public int compare(Sphere s1, Sphere s2){
        return s1.getId()-s2.getId();
    }
    
    public static void main(String[] args) {
        
    }
}


Exercise21.java



package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class Exercise21 {
    public static void main(String[] args) {
        Sphere[] sa1=Generated.array(Sphere.class,new SphereGenerator(),5);
        Sphere[] sa2=Generated.array(Sphere.class,new SphereGenerator(),10);

        System.arraycopy(sa1,2,sa2,5,3);
        sa1[3].setId(100);
        
        //未排序前
        System.out.println("Before Sort:    "+Arrays.toString(sa2));
        
        Arrays.sort(sa2, new SphereComparator());
        
        //排序后
        System.out.println("After Sort:    "+Arrays.toString(sa2));
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.