Title: Chapter 15: Generic Methods, Classes, and ArrayBased Lists
1Chapter 15 Generic Methods, Classes, and
Array-Based Lists
- Java Programming
- Program Design Including Data Structures
2Chapter Objectives
- Learn about the interfaces Cloneable and
Comparable and how to implement them - Learn about generic methods and classes
- Learn how to implement generic array-based lists
- Explore how various operations, such as search,
insert, and remove, are implemented on lists
3The interface cloneable
- Method clone of the class Object
- Protected method inherited by every class in Java
- Cannot be invoked by an object outside the
definition of its class - Provides a bit-by-bit copy of the objects data
in storage - Provides a shallow copy of objects data
- To make a deep copy of an objects data, its
class must override the clone method
4The interface cloneable (continued)
- The interface Cloneable has no method headings
that need to be implemented - Classes that implement this interface must only
redefine the clone method - Shallow copies work only when the cloned objects
contain only primitive type data or data of
immutable objects
5The interface cloneable (continued)
- Writing the clone method
- First, invoke the clone method of the super class
- Then, change the values of instance variables of
mutable types - The method clone of the class Object throws
CloneNotSupportedException
6The interface cloneable (continued)
- Example of a clone method
- public Object clone()
-
- try
-
- return super.clone() //Invoke the method clone
of - //the super class
-
- catch (CloneNotSupportedException e)
-
- return null
-
7The interface cloneable (continued)
- clone method for variables of mutable types
- public Object clone()
-
- try
-
- PersonalInfo copy (PersonalInfo)
super.clone() - copy.bDay (Date) bDay.clone()
//explicitly clone - //the
object bDay - copy.name (Person) name.clone()
//explicitly clone - //the
object name - return copy
-
- catch (CloneNotSupportedException e)
-
- return null
-
8The interface Comparable
- The interface Comparable has only one method
heading, which is compareTo - Used to force a class to provide an appropriate
definition of the method compareTo - Values of two objects of that class can be
properly compared - Example
- public class Clock implements Comparable
9The interface Comparable (continued)
- Writing the compareTo method for Clock
- public int compareTo(Object otherClock)
-
- Clock temp (Clock) otherClock
- int hrDiff hr - temp.hr
- if (hrDiff ! 0)
- return hrDiff
- int minDiff min - temp.min
- if (minDiff ! 0)
- return minDiff
- return sec - temp.sec
10The interface Comparable (continued)
- Writing the equals method for Clock
- public boolean equals(Object otherClock)
-
- Clock temp (Clock) otherClock
- return (hr temp.hr
- min temp.min
- sec temp.sec)
11The interface Comparable (continued)
- If a class implements multiple interfaces
- Separate all interfaces names using commas
- Example
- public class Clock implements Cloneable,
Comparable
12The interface Comparable (continued)
- Writing the compareTo method for Person
- public int compareTo(Object otherPerson)
-
- Person temp (Person) otherPerson
- if (firstName.equals(temp.firstName)
- lastName.equals(temp.lastName))
- return 0
- else if ((lastName.compareTo(temp.lastName) lt
0) - ((lastName.equals(temp.lastName)
- (firstName.compareTo(temp.firstName)
lt 0)))) - return -1
- else
- return 1
13The interface Comparable (continued)
- Writing the compareTo method for Date
- public int compareTo(Object otherDate)
-
- Date temp (Date) otherDate
- int yrDiff dYear - temp.dYear
- if (yrDiff ! 0)
- return yrDiff
- int monthDiff dMonth - temp.dMonth
- if (monthDiff ! 0)
- return monthDiff
- return dDay - temp.dDay
14The interface Comparable (continued)
- Writing the compareTo method for PersonalInfo
- public int compareTo(Object other)
-
- PersonalInfo temp (PersonalInfo) other
- int retValue
- retValue personID - temp.personID
- if (retValue 0)
- retValue name.compareTo(temp.name)
- if (retValue 0)
- retValue bDay.compareTo(temp.bDay)
- return retValue
15Generic Methods
- Consider the following three methods
- public static void print(int ... list)
-
- for (int elem list)
- System.out.print(elem " ")
- System.out.println()
-
list a variable-length parameter list
essentially, an array
for every element in the list
16Generic Methods (continued)
- public static void print(double ... list)
-
- for (double elem list)
- System.out.print(elem " ")
- System.out.println()
-
- public static void print(String ... list)
-
- for (String elem list)
- System.out.print(elem " ")
- System.out.println()
17Generic Methods (continued)
- Definition of the method print is identical in
each case - We can use Javas mechanism of generic methods
- Write only one definition rather than three
different definitions - Generic methods are defined using type parameters
18Generic Methods (continued)
- Type parameters
- Identifiers that specify generic type names
- Separated by commas and enclosed in angular
brackets, lt and gt - Also known as type variables
- Used to
- Declare the return type of the method
- Declare formal parameters
- Declare local variables
- Can only represent reference parameters /
variables, not primitive types (see Example 15-4)
19Generic Methods (continued)
- A skeleton form of a generic method is
- T is referred to as the type parameter
- You can declare a reference variable using the
type parameter T - ex T refVar (OK)
- You cannot instantiate objects using the type
parameter - ex refVar new T() (illigal)
20Generic Methods (continued)
- Generic definition of the method print
- public static ltTgt void print(T ... list)
//Line 1 -
- for (T elem list)
//Line 2 - System.out.print(elem " ")
//Line 3 - System.out.println()
//Line 4
21Generic Methods (continued)
- Usage example
- Integer intList 2, 3, 32, 56
- Double numList 14.56, 32.78, 11.98
- String strList "Java", "C", "Basic",
"Perl" - print(intList)
- print(numList)
- print(strList)
22Generic Methods and Bounded Type Parameters
(Skip this topic)
- There are situations when the type parameter T
must be restricted - An example generic method larger
- Finds the larger value of two objects
- Method works with built-in as well as
user-defined classes - Objects are compared using compareTo
- Method should work only with classes that provide
a definition of this method
23Generic Methods and Bounded Type Parameters
(continued)
- Definition of a generic method larger
- public static ltT extends ComparableltTgtgt
- T larger(T x, T y)
-
- if (x.compareTo(y) gt 0)
- return x
- else
- return y
24Generic Methods and Bounded Type Parameters
(continued)
- Always use the keyword extends regardless of
whether the type parameter extends a class or an
interface - If a type parameter is bounded by more than one
class (or interface) - Class names are separated using the symbol
25Generic Classes
- You can also define generic classes
- A typical form of a generic class is
- Generic classes are used to write a single
definition for a set of related classes - Also known as parametric classes
26Array-Based Lists
- A list is a collection of elements of the same
type - The length of a list is the number of elements in
the list - Example
- Hardware store list of items
- Available items
- Number of pieces in stock
- Price
27Array-Based Lists (continued)
- Common operations performed on a list
- Create the list
- Determine whether the list is empty or full
- Find the size of the list
- Destroy, or clear, the list
- Insert an item at the specified location
- Remove an item at the specified location
- Replace an item at the specified location
- Retrieve an item at the specified location
- Search the list for a given item
28Array-Based Lists (continued)interface
ArrayListADT
All 15 methods are abstract in this interface
Figure 15-1 UML class diagram of the interface
ArrayListADT
29Array-Based Lists (continued)
- The list can be sorted or unsorted
- However, the algorithms to implement certain
operations are the same - An effective, convenient, and common way to
process a list is to store it in an array
(elements are of the same type) - Initially the size of the array is larger than
the size of the list - At a later stage, the list can grow to a larger
size - We must know how full the array is
30Array-Based Lists (continued)
- Variables needed to maintain and process the list
in an array - The array, list, holding the list elements
- A variable, length, to store the length of the
list - A variable, maxSize, to store the size of the
array
31The abstract class ArrayListClass
- Implements only the operations that are common
for sorted and unsorted lists - It does not implement all the operations of the
interface ArrayListADT - We do not want to instantiate objects of this
class - The class is declared abstract
32The abstract class ArrayListClass (continued)
protected public
These 5 methods remain abstract, all others are
concrete in this class
Figure 15-2 UML class diagram of the class
ArrayListClass
33The abstract class ArrayListClass (continued)
- Definition of this class
- public abstract class ArrayListClassltTgt
implements - ArrayListADTltTgt,
Cloneable -
- protected int length //to store the length
of the list - protected int maxSize //to store the maximum
size of the - //list
- protected T list //array to hold the
list elements -
- //Place the definitions of the instance
methods and - //abstract methods here
34The abstract class ArrayListClass (continued)
- Constructor
- public ArrayListClass(int size)
-
- if (size lt 0)
-
- System.err.println("The array size must
be positive. " - "Creating an array of
size 100. ") - maxSize 100
-
- else
- maxSize size
- length 0
- list (T) new ObjectmaxSize
35The abstract class ArrayListClass (continued)
- Method removeAt (int k)
- remove the element at position k
k
0 1 2 3 4 5
6 7
list
35
24
45
17
26
78
0 1 2 3 4 5
6 7
list
35
24
45
17
26
78
after the method call removeAt
36The abstract class ArrayListClass (continued)
- Method removeAt
- public void removeAt(int k)
-
- if (k lt 0 k gt length)
- System.err.println("The location of the
item to " - "be removed is out of
range.") - else
-
- for (int i k i lt length - 1 i)
- listi listi 1
- listlength - 1 null
- length--
-
- //end removeAt
37The abstract class ArrayListClass (continued)
- Method retrieveAt
- public T retrieveAt(int location)
-
- if (location lt 0 location gt length)
-
- System.err.println("The location of the
item to be " - "retrieved is out of
range.") - return null
-
- else
- return listlocation
- //end retrieveAt
38Unordered ListsThe UnorderedArrayList class (a
concrete class)
These 5 methods are implemented in
UnorderedArrayList here, all methods are concrete
now
Figure 15-4 UML class diagram of the class
UnorderedArrayList and the
inheritance hierarchy
39Unordered Lists (continued)
- Definition of this class
- public class UnorderedArrayListltTgt extends
ArrayListClassltTgt -
- //Place the definitions of the methods and
the - //constructors here.
40Unordered Lists (continued)
- Constructors
- //Default constructor
- public UnorderedArrayList()
-
- // call the constructor of the superclass
(see p. 660) - super()
-
- //Constructor with a parameter
- public UnorderedArrayList(int size)
-
- // call the constructor of the superclass
(see p. 661) - super(size)
41Unordered Lists (continued)
- Method insertAt
- public void insertAt(int k, T insertItem)
-
- if (k lt 0 k gt maxSize)
- System.err.println("The position of the
item to " - "be inserted is out of
range.") - else if (length gt maxSize) //list is full
- System.err.println("Cannot insert in a
full list.") - else
-
- for (int i k i gt k i--)
- listi listi - 1 //move the
elements down - listk insertItem
- length //increment the length
-
- //end insertAt
42Unordered Lists (continued)
- Method insertEnd
- public void insertEnd(T insertItem)
-
- if (length gt maxSize) //list is full
- System.err.println("Cannot insert in a
full list.") - else
-
- listlength insertItem
- length //increment the length
-
- //end insertEnd
43Unordered Lists (continued)
- Method seqSearch
- public int seqSearch(T searchItem)
-
- int loc
- boolean found false
- for (loc 0 loc lt length loc)
- if (listloc.equals(searchItem))
- // DO NOT use because each
listloc and searchItem - // are references to objects of type
Double -
- found true
- break
-
- if (found)
- return loc
- else
- return -1
- //end seqSearch
44Unordered Lists (continued)
- Method replaceAt
- public void replaceAt (int k, T repItem)
-
- if (k lt 0 k gt maxSize)
- System.err.println("The position of the
item to " - "be replaced is out of
range.") - else if (length gt maxSize) //list is full
- System.err.println("Cannot insert in a
full list.") - else
-
- listk repItem
-
- //end insertAt
45Unordered Lists (continued)
- Method remove
- public void remove(T removeItem)
-
- int loc
- if (length 0)
- System.err.println("Cannot delete from an
" "empty list.") - else
-
- loc seqSearch(removeItem)
- if (loc ! -1)
- removeAt(loc)
- // This method is inherited from
ArrayListClass - else
- System.out.println("The item to be
deleted " - "is not in the
list.") -
- //end remove
46Ordered List The OrderedArrayList class (a
concrete class)
Figure 15-4 UML class diagram of the class
OrderedArrayList and the
inheritance hierarchy
47Ordered List (continued)
- Class definition
- public class OrderedArrayList ltTgt extends
ArrayListClassltTgt -
- // Place constructor and method definitions
- // here.
48Ordered List (continued)
- Constructors
- //Default constructor
- public OrderedArrayList()
-
- super()
-
- //Constructor with a parameter
- public OrderedArrayList(int size)
-
- super(size)
49Ordered List (continued)
- Method seqSearch
- public int seqSearch(T searchItem)
-
- int loc
- boolean found false
- for (loc 0 loc lt length loc)
-
- ComparableltTgt temp (ComparableltTgt)
listloc - if (temp.compareTo(searchItem) gt 0)
-
- found true
- break
-
-
- if (found)
-
- if (listloc.equals(searchItem)) return
loc - else return -1
-
50Ordered List (continued)
- Method insert
- public void insert(T insertItem)
-
- int loc
- boolean found false
- if (length 0) //list is empty
- listlength insertItem //insert
insertItem - //and
increment length - else if (length maxSize)
- System.err.println("Cannot insert in a
full list.") -
51Ordered List (continued)
- Method insert (continued)
- else
-
- for (loc 0 loc lt length loc)
-
- ComparableltTgt temp (ComparableltTgt)
listloc - if (temp.compareTo(insertItem) gt 0)
-
- found true
- break
-
-
- for (int i length i gt loc i--)
- listi listi - 1 //move the
elements down - listloc insertItem //insert
insertItem - length //increment the length
-
- //end insert
52Programming Example Polynomial Operations
- Write a class that implements the following basic
operations performed on polynomials - Evaluating a polynomial
- Adding polynomials
- Subtracting polynomials
- Multiplying polynomials
- Dividing polynomials
53Chapter Summary
- Cloneable interface
- clone method makes a bit-by-bit copy of the
object - Classes can override this method to provide a
deep copy - Comparable interface
- Used to force classes to implement the compareTo
method - Objects can be properly compared using the
compareTo method
54Chapter Summary (continued)
- Generic methods
- Created using type parameters
- Allow use of restricted type parameters
- Generic classes
- Array-based lists
- Lists are collection of elements of the same type
- Arrays provide a convenient way to implement
lists - Lists can be either unsorted or sorted