Java Reference
In-Depth Information
ssl.add(new Circle(100, 200, 300));
ssl.add(new Circle(10, 20, 30));
Listing 3-53 ' s Circle class extends Shape and implements the
java.lang.Comparable interface,whichisusedtospecifythe natural ordering of
Circle objects.Theinterface's compareTo() methodimplementsthisorderingby
returning a value to reflect the order:
• A negative value is returned if the current object should precede the object
passed to compareTo() in some fashion.
• A zero value is returned if the current and argument objects are the same.
• A positive value is returned if the current object should succeed the argument
Circle 'soverriding compareTo() methodcomparestwo Circle objectsbased
ontheirradii.Thismethodordersa Circle instancewiththesmallerradiusbeforea
Circle instance with a larger radius.
The SortedShapesList class specifies <S extends
Shape&Comparable<S>> asitsparameterlist.Theactualtypeargumentpassedto
the S parameter must subclass Shape , and it must also implement the Comparable
Note A type parameter bound that includes the type parameter is known as a
recursive type bound . For example, Comparable<S> in S extends
Shape&Comparable<S> isarecursivetypebound.Recursivetypeboundsarerare
andtypicallyshowupinconjunctionwiththe Comparable interface,forspecifying
a type's natural ordering.
Circle satisfiesbothcriteria:itsubclasses Shape andimplements Comparable .
Asaresult,thecompilerdoesnotreportanerrorwhenitencountersthe main() meth-
od's SortedShapesList<Circle> ssl = new SortedShapesList<>();
calledsafely.Forexample, sort() cancall Comparable 's compareTo() method.
the two Circle objects are sorted in ascending order of radius:
Search WWH ::

Custom Search