Java Reference
In-Depth Information
Example 2•9: Sorter.java (continued)
Math.random()*10);
// Now sort it using the SortableComplexNumber compareTo() method,
// which sorts by magnitude, and print the results out.
System.out.println("Sorted by magnitude:");
Sorter.sort(a);
for(int i = 0; i < a.length; i++) System.out.println(a[i]);
// Sort the complex numbers again, using a Comparer object that
// compares them based on the sum of their real and imaginary parts
System.out.println("Sorted by sum of real and imaginary parts:");
Sorter.sort(a, new Sorter.Comparer() {
public int compare(Object a, Object b) {
ComplexNumber i = (ComplexNumber)a;
ComplexNumber j = (ComplexNumber)b;
return sign((i.real() + i.imaginary()) -
(j.real() + j.imaginary()));
}
});
for(int i = 0; i < a.length; i++) System.out.println(a[i]);
// Sort them again using a Comparer object that compares their real
// parts, and then their imaginary parts
System.out.println("Sorted descending by real, then imaginary:");
Sorter.sort(a, 0, a.length-1, false, new Sorter.Comparer() {
public int compare(Object a, Object b) {
ComplexNumber i = (ComplexNumber) a;
ComplexNumber j = (ComplexNumber) b;
double result = i.real() - j.real();
if (result == 0) result = i.imaginary()-j.imaginary();
return sign(result);
}
});
for(int i = 0; i < a.length; i++) System.out.println(a[i]);
}
/** This is a convenience routine used by comparison routines */
public static int sign(double x) {
if (x > 0) return 1;
else if (x < 0) return -1;
else return 0;
}
}
}
Exercises
2-1. Write a Circle class that is similar to the Rect class. Define a move() method
and an isInside() method. (Recall that a circle is defined as all points within
a given radius from the center. Test for insideness by using the Pythagorean
theorem to compute the distance between a point and the center of the cir-
cle.) Also, define a boundingBox() method that returns the smallest Rect that
encloses the complete Circle . Write a simple program to test the methods
you've implemented.
Search WWH ::




Custom Search