Download Abstract Classes and Interfaces

Document related concepts
no text concepts found
Transcript
Chapter 15 Abstract Classes and
Interfaces
1
Outlines
• abstract methods and abstract classes
• Design and use of abstract classes (§15.2).
– Calendar and GregorianCalendar classes (§15.4).
• Design and Use of Interface (§15.5).
– Define an order using the Comparable interface (§15.6).
– The ActionListener interface ((§14.6 old).
– make objects cloneable using the Cloneable interface (§15.7).
• Abstract class vs. interface (§15.8).
• Use wrapper classes (Byte, , Integer,Double, …) to wrap primitive
data values into objects (§14.9 old; 15.3 ).
• BigInteger and BigDecimal (§15.3).
• Create a generic sort method (§14.10 old).
• AutoBoxing between primitive types and wrapper class types
(§14.11 old).
2
The abstract Modifier
• can appear in the head of a class or method
– represent an abstarct class/method
• The abstract class
–
–
–
–
represent a partial implementation
represent a common part of many subclasses
Cannot be instantiated ( via new XXX(…) )
Should be extended and implemented in subclasses
• The abstract method
– has only method signature but no
implementation
– represent a (hook) method to be implemented by subclasses
– can be used as part of a use-implement contract.
– can represent an operation that must be implemented but are
not provided due to lack of detailed information.
3
From Chapter 11
GeometricObject
-color: String
The color of the object (default: white).
-filled: boolean
Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date
The date when the object was created.
+GeometricObject()
Creates a GeometricObject.
+getColor(): String
Returns the color.
+setColor(color: String): void
Sets a new color.
+isFilled(): boolean
Returns the filled property.
+setFilled(filled: boolean): void
Sets a new filled property.
+getDateCreated(): java.util.Date
Returns the dateCreated.
+toString(): String
Returns a string representation of this object.
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+getRadius(): double
+Rectangle(width: double, height: double)
+setRadius(radius: double): void
+getWidth(): double
+getArea(): double
+setWidth(width: double): void
+getPerimeter(): double
+getHeight(): double
+getDiameter(): double
+setHeight(height: double): void
• getArea() and getPerimeter ()
are common to all subclasses
and hence should be lifted to
the GeometricObject.
• Issues:
1. Unable to implement them
due to lack of details,
2. Still valuable as a contract
for subclasses to implement.
+getArea(): double
+getPerimeter(): double
4
Abstract Classes
GeometricObject
-color: String
-filled: boolean
The # sign indicates
protected modifer
-dateCreated: java.util.Date
#GeometricObject()
+getColor(): String
+setColor(color: String): void
• According to UML, the name of abstract
class/method must be italicized.
• Methods getArea() and getPerimeter() are
overridden in Circle and Rectangle.
• Overriding methods in subclasses can be
omitted in the UML diagram.
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
+getArea(): double
+getPerimeter(): double
GeometricObject
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+getRadius(): double
+Rectangle(width: double, height: double)
+setRadius(radius: double): void
+getWidth(): double
+getDiameter(): double
+setWidth(width: double): void
+getHeight(): double
Circle
Rectangle
TestGeometricObject
+setHeight(height: double): void
5
NOTE
•We call a class/method concrete if it is not abstract.
• An abstract method can appear only in an abstract
class; it cannot appear in a concrete class. However, it
is possible to declare an abstract class even if it
contains no abstract method.
abstract class C { …
abstract void m(); …
}
abstract class C {…/*all methods are concrete*/ …}
• If class CC1 C2 … Cn and there are abstract
methods left from C1,…Cn that are not implemented
in C, then C must be declared as abstract.
6
NOTE
•An abstract class cannot be instantiated using the new
operator since it is still incomplete.
•But you still need to define its constructors, which are
invoked in the constructors of its subclasses.
abstract class Parent
{ Parent() {…}
… }
class Child extends Parent { Child(){super();…}… }
Ex: Constructors of abstract GeometricObject class are
invoked in the Circle class and the Rectangle class.
7
NOTE
•A subclass can be abstract even if its superclass
is concrete.
Abstract
Concrete
Concrete
Abstract
•For example, the Object class is concrete, but
its subclasses, such as GeometricObject, may be
abstract.
8
NOTE
•A subclass can override a method from its
superclass to declare it abstract. Ex:
public abstract class O1 extends Object {
public abstract boolean equals(Object o) ;
…}
•This is rare, but useful when the implementation of
the method in the superclass becomes invalid in the
subclass.
•In this case, the subclass must be declared abstract.
9
NOTE
• Abstract class can still be used as the type of variables
or array elements. Ex:
GeometricObject[] geo = new GeometricObject[10];
GeomtricObject c1 = new Circle(10) ;
• Note the syntax difference between an abstract method
and a concrete do-nothing method:
• public abstract void m1() ; // abstract method
• public void m2 () { } // concrete method
10
Example: Using the GeometricObject Class
• Creates two geometric objects: a circle, and a
rectangle,
• Invokes the equalArea method to check if the two
objects have equal area, and
• invokes the displayGeometricObject method to
display the objects.
TestGeometricObject
11
15.4
Date, Calendar and GregorianCalendar
• All defined in package java.util.
– replaced by java.time since java 8 (java.time introduction)
• All represent a specific instant in time with
millisecond precision since 1970,1,1.
• Calendar is an abstract base class for extracting
detailed calendar information :
– year, month, date, hour, minute, second.
– possible calendars: lunar calendar, Jewish calendar
• GregorianCalendar is a concrete implementation of
Calendar for Gregorian calendar (supported in jdk).
• Date is deprecated since it is not amenable to
internationalization (i18n).
12
The Abstract Calendar Class and Its
GregorianCalendar subclass
java.util.Calendar
#Calendar()
Constructs a default calendar.
+get(field: int): int
Returns the value of the given calendar field.
+set(field: int, value: int): void
Sets the given calendar to the specified value.
+set(year: int, month: int,
dayOfMonth: int): void
Sets the calendar with the specified year, month, and date. The month
parameter is 0-based, that is, 0 is for January.
+getActualMaximum(field: int): int
Returns the maximum value that the specified calendar field could have.
+add(field: int, amount: int): void
Adds or subtracts the specified amount of time to the given calendar field.
+getTime(): java.util.Date
Returns a Date object representing this calendar’s time value (million
second offset from the Unix epoch).
+setTime(date: java.util.Date): void Sets this calendar’s time with the given Date object.
java.util.GregorianCalendar
+GregorianCalendar()
Constructs a GregorianCalendar for the current time.
+GregorianCalendar(year: int,
month: int, dayOfMonth: int)
Constructs a GregorianCalendar for the specified year, month, and day of
month.
+GregorianCalendar(year: int,
Constructs a GregorianCalendar for the specified year, month, day of
month: int, dayOfMonth: int,
month, hour, minute, and second. The month parameter is 0-based, that
hour:int, minute: int, second: int)
is, 0 is for January.
13
The GregorianCalendar Class
•static Calendar.getInstance([TimeZone][,Locale]).
–static method to get current date-time.
•Constructors:
–GregorianCalendar() : construct a default GregorianCalendar
with the current time
–GregorianCalendar(int year, month, date)
–GregorianCalendar(int year, month, date, hour, minut, second)
• Note: The month parameter is 0-based, i.e., 0 is for
January.
14
The get/set Method in Calendar Class
• get(int field) : int ; set(int field, int value)
– get() used to extract the value for a given time field.
– set() used to modified filed value.
•Possible time fields are defined as constants :
Constant
Description
YEAR
MONTH
DATE
HOUR
HOUR_OF_DAY
MINUTE
SECOND
DAY_OF_WEEK
DAY_OF_MONTH
DAY_OF_YEAR
The year of the calendar.
The month of the calendar with 0 for January.
The day of the calendar.
The hour of the calendar (12-hour notation).
The hour of the calendar (24-hour notation).
The minute of the calendar.
The second of the calendar.
The day number within the week with 1 for Sunday.
Same as DATE.
The day number in the year with 1 for the first
day of the year.
The week number within the month.
The week number within the year.
Indicator for AM or PM (0 for AM and 1 for PM).
WEEK_OF_MONTH
WEEK_OF_YEAR
AM_PM
15
Example
Calendar cal = new GregorianCalendar();
// or Calendar cal = Calendar.getInstance([ Locale.TAIWAN ] ) ;
out.println(cal.get(Calendar.YEAR));
out.println(cal.get(Calendar.MONTH));
out.println(cal.get(Calendar.DATE));
out.println(cal.get(Calendar.HOUR));
out.println(cal.get(Calendar.HOUR_OF_DAY));
out.println(cal.get(Calendar.DAY_OF_WEEK));
out.println(cal.get(Calendar.WEEK_OF_MONTH));
out.println(cal.get(Calendar.DAY_OF_MONTH));
…
TestCalendar
16
15.5 Interfaces
• What is an interface? Why is an interface useful?
• How to declare an interface?
• How to implement an interface ?
• How to use an interface?
17
What is an interface ?
• a class-like construct that contains only constants and
abstract methods (but no constructor/variable /concrete
method).
–But may have default/static methods since Java8
• Java's mechanism to enable unrelated classes/objects to
have common behavior. Ex: Applications may need
instances of some classes to be
– comparable/ cloneable
– edible/drinkable etc.
-- serializable/persistable.
•Approaches:
–1. extract the set of methods/constants common to all relevant
classes as an interface ( as a contract between users/
implementors of the interface ).
– 2. Individual classes needing the common behavior should
implement the interface and can then be casted to that type. 18
Declare an Interface
To distinguish an interface from a class, Java uses the
following syntax to declare an interface:
[public|private] interface IfName [
extends If1,…,Ifn ]
{ constant declarations…
abstract method signatures…
concrete default methods…
}
Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
19
Implement an interface
• Once an interface named If has been declared, we can
implement it in a class C using the implements clause:
class C extends C0 implements If,If2…,Ifn { … }
• Ex : Since we have declare the Edible interface, we can
now implement it in the classes Chicken and Fruit in
Listing 14.6.
Edible
TestEdible
20
Interface is a Special Class
• An interface is treated like an abstract class in Java.
– compiled into a bytecode file.
– cannot create instances using the new operator,
– can be used as types of variables.
– Edible e ;
–can be the target type of a cast operation.
– Apple ap = new Apple(); // suppose Apple implements Edible.
– if ( ap instanceof Edible ) e = (Edible) ap;
•But
– can extend one (or more) super interfaces.
– has no constructor.
– while a class can extends at most one super class it can
implement zero or more interfaces.
21
Default Modifiers in Interfaces
–All data fields are default to be public final static
–all methods are default be public abstract (unless they are
default methods).
public interface T1 {
public static final int K = 1;
Equivalent
public interface T1 {
int K = 1;
void p();
public abstract void p();
}
}
• A constant c defined in an interface If can be accessed using
syntax If.c. (ex: T1.K )
• The 'public' modifier before the interface keyword cannot be
omitted if it is public.
22
Define Interfaces
• Want a unifying way to find the larger of two
objects from one of many classes.
–Objects can be students, dates, or circles.
•approach:
1.Define a generic compareTo(Object) method to
determine the order of the two objects.
2.Wrap the method as an interface
3.Require each class needing such behavior to
implement the interface.
– Ex: use student ID as the key for comparing students,
radius as the key for comparing circles, and volume as
the key for comparing dates.
23
15.6 The Comparable Interface
// This interface is defined in java.lang
package
package java.lang;
public interface Comparable {
/* return :
negative value => this < o
positive value => this > o
0 => this = o */
public int compareTo(Object o);
//default methods(not part of original Comparable!)
default public boolean lessThan(Object) {
return compareTo(o) < 0 ;}
}
24
String and Date Classes
•Many classes (e.g., String and Date) in the Java library
implement Comparable to define a natural order for the
objects.
• instanceof can also be used to test if an object
implements an interface.
public class String extends Object
implements Comparable {
// class body omitted
public class Date extends Object
implements Comparable {
// class body omitted
}
}
new
new
new
new
String() instanceof String
String() instanceof Comparable
java.util.Date() instanceof java.util.Date
java.util.Date() instanceof Comparable
25
Generic max Method
// Max.java: Find a maximum object
public class Max {
/** Return the maximum of two objects */
public static Comparable max
(Comparable o1, Comparable o2) {
if (o1.compareTo(o2) > 0)
return o1;
else
return o2;
}
}
(a)
String s1 = "abcdef";
String s2 = "abcdee";
String s3 = (String)Max.max(s1, s2);
// Max.java: Find a maximum object
public class Max {
/** Return the maximum of two objects */
public static Object max
(Object o1, Object o2) {
if (((Comparable)o1).compareTo(o2) > 0)
return o1;
else
return o2;
}
}
(b)
Date d1 = new Date();
Date d2 = new Date();
Date d3 = (Date)Max.max(d1, d2);
The return value from the max method is of the Comparable
type. So, you need to cast it to String or Date explicitly.
26
Cast to/from an interface
• If class C implements interface If, then
– every object of C can be assigned to a variable of the type
If without the need to cast. On the other hand,
– to assign a If object to a C variable, we need explicit cast.
• Ex:
String s = "abc";
Comparable c1 = s ; // fine
Comparable c2 = (Comparable) s ; // fine
String s1 = c1 ; // error
String s2 = (String) c2 // fine
27
Declaring Classes to Implement Comparable
Notation:
The interface name and the
method names are italicized.
The dashed lines and hollow
triangles are used to point to
the interface.
GeometricObject
Rectangle
-
extends
ComparableRectangle
-
«interface»
java.lang.Comparable
+compareTo(o: Object): int
implements
ComparableRectangle
You cannot use the max method to find the larger of two instances of Rectangle,
because Rectangle does not implement Comparable. However, you can declare a
new rectangle class that implements Comparable. The instances of this new
class are comparable. Let this new class be named ComparableRectangle.
ComparableRectangle rectangle1 = new ComparableRectangle(4, 5);
ComparableRectangle rectangle2 = new ComparableRectangle(3, 6);
System.out.println(Max.max(rectangle1, rectangle2));
28
15.8 Interfaces vs. Abstract Classes
–In an interface, the data must be constants; an abstract class can
have all types of data.
–Each method in an interface has only a signature without
implementation; an abstract class can have concrete methods.
Abstract
class
Fields
Constructors
Methods
No
restrictions
Constructors are invoked by
subclasses through constructor
chaining. An abstract class cannot
be instantiated using the new
operator.
No restrictions.
Interface All variables No constructors. An interface
must be
cannot be instantiated using the
public static new or super operator.
final
1. public abstract
instance methods
2.default public
instance methods
3. static public
29
methods
Interfaces vs. Abstract Classes, cont.
• A class can extend only one superclass but can implement
more than one interfaces.
public class C1 extends C implements If1,If2,…Ifn {…}
• An interface can extend zero or more interfaces.
public interface If extends If1,If2,…Ifn {…}
• Like a class, an interface also defines a type.
• A variable of an interface type can reference any instance of
the class that implements the interface.
• If a class extends an interface, this interface plays the same
role as a superclass. You can use an interface as a data type and
cast a variable of an interface type to its subclass, and vice versa.
30
Interfaces vs. Abstract Classes, cont.
Interface1_2
Interface1_1
Object
Interface2_2
Interface1
Class1
Interface2_1
Class2
If c is an instance of Class2, then c is also an instance of Object,
Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and
Interface2_2.
C1 c1= new C1(); C2 c2 = new C2();
If2_2 if22 = c2;
If1_2 if12 = c1;
if22 = c1 // complie-error
If22 = (C2) c1 // runtime error

31
Caution: conflict interfaces
– In rare occasions, a class may implement two interfaces
with conflict information
• (e.g., two same constants with different values or two
methods with same signature but different return type).
interface IF1 { final static int COUNT = 2; int m1() ; }
interface IF2 { final staic String COUNT = "abc"; void m1(); }
class A implements If1,If2 {…}
– This type of errors will be detected by the compiler.
32
Use an interface or a class?
– a strong is-a relationship that clearly describes a parent-child
relationship should be modeled using classes.
–Ex: Every apple is a fruit; A manager is an employee. So their
relationship should be modeled using class inheritance.
–A weak is-a relationship, also known as an is-kind-of relationship,
indicates that an object possesses a certain property. A weak is-a
relationship can be modeled using interfaces.
–Ex: All strings are comparable, so the String class implements the
Comparable interface.
–Can also use interfaces to circumvent single inheritance restriction
if multiple inheritance is desired.
–Simple rule: noun  class ; adjective  interface
33
Creating Custom Interfaces
public interface Edible {
/** Describe how to eat */
public String howToEat();
}
class Animal {
}
class Chicken extends Animal
implements Edible {
public String howToEat() {
return "Fry it";
}
}
class Tiger extends Animal {
}
class abstract Fruit
implements Edible {
}
class Apple extends Fruit {
public String howToEat() {
return "Make apple cider";
}
}
class Orange extends Fruit {
public String howToEat() {
return "Make orange juice";
}
}
34
Implements Multiple Interfaces
class Chicken extends Animal implements Edible, Comparable {
int weight;
public Chicken(int weight) {
this.weight = weight;
}
public String howToEat() {
return "Fry it";
}
public int compareTo(Object o) {
return weight – ((Chicken)o).weight;
}
}
35
Creating Custom Interfaces, cont.
• Show Ediable objects
public interface Edible {
/** Describe how to eat */
public String howToEat();
}
public class TestEdible {
public static void main(String[] args) {
Object[] objects = {new Tiger(), new Chicken(), new
Apple()};
for (int i = 0; i < objects.length; i++)
showObject(objects[i]);
}
public static void showObject(Object object) {
if (object instanceof Edible)
System.out.println(((Edible)object).howToEat());
}
}
36
15.7 The Cloneable Interfaces
• Marker Interfaces: are interfaces with empty body (containing no
constants or methods. )
• used to denote that a class possesses certain desirable properties.
•A class that implements the Cloneable interface is marked
cloneable, and its objects can be cloned using the clone() method
defined in the Object class.
•Once you declare a class Cloneable, you have the right to
implement/refine the protected Object clone() method.
package java.lang;
public interface Cloneable {
}
37
Examples
Many classes (e.g., Date and Calendar) in the Java library implement
Cloneable. Thus, the instances of these classes can be cloned. For
example, the following code
Calendar calendar = new GregorianCalendar(2003, 2, 1);
Calendar calendarCopy = (Calendar)calendar.clone();
System.out.println("calendar == calendarCopy is " +
(calendar == calendarCopy));
System.out.println("calendar.equals(calendarCopy) is " +
calendar.equals(calendarCopy));
displays
calendar == calendarCopy is false
calendar.equals(calendarCopy) is true
38
Implementing Cloneable Interface
•Declare a custom class that implements the Cloneable
interface.
•The class must override the clone() method from the
Object class.
•The following code declares a class named House that
implements Cloneable and Comparable.
House
39
Shallow vs. Deep Copy
House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
• Object.clone() is a shallow copy
• Implement your own clone() if you want deep copy.
house1: House
id = 1
area = 1750.50
whenBuilt
Memory
1
1750.50
reference
date object contents
house2 = house1.clone()
house2: House
id = 1
whenBuilt: Date
Memory
area = 1750.50
1
1750.50
whenBuilt
reference
40
deep clone() for House
public House clone() { // House ok! covariant
House h = super.clone() ; // h is a shallow copy
Date d = whenBuilt.clone() ; // suppose it is
deep copy!
h.whenBuilt = d;
return h ;
} // override #Object.clone(): Object
41
Wrapper Classes
• Boolean

• Character

Integer
Long
• Short

Float
• Byte

Double
NOTES:
(1) The wrapper classes do not
have no-arg constructors.
(2) The instances of all wrapper
classes are immutable, i.e., their
internal values cannot be changed
once the objects are created.
Comparable
-
Object
Number
Character Boolean
-
-
Double
-
Float
-
Long
-
Integer
-
Short
-
Byte
42
The toString, equals, and hashCode
Methods
• All overrides the toString, equals, and
hashCode methods defined in the Object
class.
• All implement the Comparable interface
–the compareTo method is implemented in these
classes.
43
15.3 The Number Class
•Extended by all nemuric wrapper classes.
•contains 4 abstract + 2 concrete methods:
– doubleValueA(), floatValueA(), intValueA(), longValueA(),
shortValue(), and byteValue().
• These methods “convert” objects into primitive type
values.
•byte byteValue() { return (byte)intValue(); }
•short shortValue() {return (short)intValue() ; }
•In template design pattern, shortValue&byteValue() are
called template methods, while other abstract methods are
called hook methods.
44
The Integer and Double Classes
java.lang.Number
+byteValue(): byte
+shortValue(): short
+intValue(): int
+longVlaue(): long
+floatValue(): float
+doubleValue():double
java.lang.Comparable
+compareTo(o: Object): int
java.lang.Integer
-value: int
+MAX_VALUE: int
+MIN_VALUE: int
+Integer(value: int)
+Integer(s: String)
+valueOf(s: String): Integer
+valueOf(s: String, radix: int): Integer
+parseInt(s: String): int
+parseInt(s: String, radix: int): int
java.lang.Double
-value: double
+MAX_VALUE: double
+MIN_VALUE: double
+Double(value: double)
+Double(s: String)
+valueOf(s: String): Double
+valueOf(s: String, radix: int): Double
+parseDouble(s: String): double
+parseDouble (s: String, radix: int): double
45
The Integer Class
and the Double Class
• Constructors
• Class Constants MAX_VALUE, MIN_VALUE
• Conversion Methods
46
Numeric Wrapper Class Constructors
•can construct a wrapper object either from
– a primitive data type value or from
– a string representing the numeric value.
•The constructors for Integer and Double are:
public Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)
47
Numeric Wrapper Class Constants
•Each has the constants MAX_VALUE and MIN_VALUE.
• MAX_VALUE represents the maximum primitve value
of the corresponding primitive data type.
•MIN_VALUE represents
– the minimum byte, short, int, and long values or
–the minimum positive float and double values.
•Ex: Integer.MAX_VALUE == 2,147,483,647
– Float.MIN_VALUE =1.4E-45), and
–Dobule.MAX_VALUE == 1.79769313486231570e+308d).
48
Conversion Methods
•Each numeric wrapper class implements the
abstract methods
–doubleValue, floatValue, intValue, longValue, and
shortValue,
which are defined in the Number class.
•These methods “convert” wrapper objects
into primitive type values.
49
The Static valueOf Methods
•Each numeric wrapper classes has a useful class
method, valueOf(String s).
•This method creates a new object initialized to
the value represented by the specified string.
•Ex:
– Double doubleObject = Double.valueOf("12.4");
– Integer integerObject = Integer.valueOf("12");
50
From Strings to primitive numbers
•static methods that have been used:
–Integer.parseInt(String ): int
–Double.parseDouble(String): double
• Each wrapper class has two parsing methods,
– parseXxx(String [, int radix]): xxx
–xxx is {int, long, float, dobule, short, byte} and
–Xxx is xxx with first x capitalized
to parse a numeric string into an appropriate
numeric value.
51
Summary of conversion methods among primitive types,
String and their Wrapper classes
---- static methods
toString() ; String.valueOf(Object)
String
Type1.decode(String)
Type1.valueOf(s [,radix])
new Type1(s [,radix])
----- instance method
----- constructor
Type1
t2Value()
t2
new Type1(t1)
Type1.parseT1(s [,r])
Type1.toString(t1 [, r])
Type1.toBinaryString()
Type1.toOctalString()
Type1.toHexString()
t1
Note:
t1 = int =>
(Type1,
T1 )==
(Integer,Int )
Non-floating type only!
Converting methods among int, String and Integer
----- static methods
toString() ;
String.valueOf(.)
----- instance method
----- constructor
String
Integer.decode(String)
Integer.valueOf(s [,radix])
new Integer(s [,radix]) Integer longValue()
intValue()
long
new Integer(int)
Integer.parseInteger(s [,r])
Integer.toString(t1 [, r])
Integer.toBinaryString()
Integer.toOctalString()
Integer.toHexString()
Note:
t1 = int =>
int
• Type1 =
Integer
• T1 = Int
For non-floating types only
Example: Sorting an Array of Objects
• The example presents a generic method for
sorting an array of objects.
• The objects are supposed to be instances of the
Comparable interface and they are compared
using the compareTo method.
GenericSort
54
TIP
•Java provides a static sort method for sorting an
array of Object in the java.util.Arrays class.
–Arrays.sort( Object[] [, int from, int to] )
– //members assumed to imeplement Comparable
• Also provide sort methods for arrays of primitive
types:
– java.util.Arrays.sort(xxx[] array [, int from, int to]);
– where xxx is any primitive type except boolean.
55
NOTE: subtypes relations for arrays
• Arrays are objects. ( xxx[]  Object )
– An array is an instance of the Object class.
•If A … B…Object, every instance of A[] is an
instance of B[].
– A  B  A[]  B[]
•The followings are true:
–new int[10] instanceof Object
–new GregorianCalendar[10] instanceof Calendar[];
–new Calendar[10] instanceof Object[]
–new Calendar[10] instanceof Object
– Exception: int  long but
int[] ! long[]
–
Integer !  Long ( but Integer  Number )
56
CAUTION
• Although an int value can be assigned to a double type
variable, int[] and double[] are two incompatible types.
• Therefore, you cannot assign an int[] array to a variable
of double[] or Object[] type.
–double[] d = new int[]{…}; // compile-time error!
–Object[] os = new int[]{…} // error
–Object[] os = new Integer[10]; // ok!
57
Automatic Conversion Between Primitive Types and
Wrapper Class Types
AutoBoxing and unboxing :
JDK 1.5 allows primitive type and wrapper classes to be converted automatically.
For example, the following statement in (a) can be simplified as in (b):
Integer[] intArray = {new Integer(2),
new Integer(4), new Integer(3)};
(a)
Equivalent
Integer[] intArray = {2, 4, 3};
New JDK 1.5 boxing
(b)
Integer[] intArray = {1, 2, 3};
System.out.println(intArray[0] + intArray[1] + intArray[2]);
Unboxing
58
10.14 BigInteger and BigDecimal
• If you need very large integers or high precision
floating-point values, you can use the BigInteger
and BigDecimal classes in the java.math package.
•Both are immutable.
•Both extend the Number class and implement
the Comparable interface.
59
BigInteger and BigDecimal
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
LargeFactorial
BigDecimal a = new BigDecimal(1.0);
BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
60