Download presentation
Published byMia Molton Modified over 9 years ago
1
Chapter 15: Generic Methods, Classes, and Array-Based Lists
Java Programming: Program Design Including Data Structures
2
Chapter 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 Java Programming: Program Design Including Data Structures
3
The 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 object’s data in storage Provides a shallow copy of object’s data To make a deep copy of an object’s data, its class must override the clone method Java Programming: Program Design Including Data Structures
4
The 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 Java Programming: Program Design Including Data Structures
5
The 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 Java Programming: Program Design Including Data Structures
6
The 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; Java Programming: Program Design Including Data Structures
7
The 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; Java Programming: Program Design Including Data Structures
8
The 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 Java Programming: Program Design Including Data Structures
9
The 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; } Java Programming: Program Design Including Data Structures
10
The 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); } Java Programming: Program Design Including Data Structures
11
The interface Comparable (continued)
If a class implements multiple interfaces Separate all interfaces names using commas Example public class Clock implements Cloneable, Comparable Java Programming: Program Design Including Data Structures
12
The 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) < 0) || ((lastName.equals(temp.lastName) && (firstName.compareTo(temp.firstName) < 0)))) return -1; else return 1; } Java Programming: Program Design Including Data Structures
13
The 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; } Java Programming: Program Design Including Data Structures
14
The 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); retValue = bDay.compareTo(temp.bDay); return retValue; } Java Programming: Program Design Including Data Structures
15
Generic Methods Consider the following three methods:
public static void print(int ... list) { for (int elem : list) System.out.print(elem + " "); System.out.println(); } Java Programming: Program Design Including Data Structures
16
Generic 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) Java Programming: Program Design Including Data Structures
17
Generic Methods (continued)
Definition of the method print is identical in each case We can use Java’s mechanism of generic methods Write only one definition rather than three different definitions Generic methods are defined using type parameters Java Programming: Program Design Including Data Structures
18
Generic Methods (continued)
Type parameters Identifiers that specify generic type names Separated by commas and enclosed in angular brackets, < and > Also known as type variables Used to Declare the return type of the method Declare formal parameters Declare local variables Cannot represent primitive types Java Programming: Program Design Including Data Structures
19
Generic 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 You cannot instantiate objects using the type parameter Java Programming: Program Design Including Data Structures
20
Generic Methods (continued)
Generic definition of the method print public static <T> void print(T ... list) //Line 1 { for (T elem : list) //Line 2 System.out.print(elem + " "); //Line 3 System.out.println(); //Line 4 } Java Programming: Program Design Including Data Structures
21
Generic 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); Java Programming: Program Design Including Data Structures
22
Generic Methods and Bounded Type Parameters
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 Java Programming: Program Design Including Data Structures
23
Generic Methods and Bounded Type Parameters (continued)
Definition of a generic method larger public static <T extends Comparable<T> > T larger(T x, T y) { if (x.compareTo(y) >= 0) return x; else return y; } Java Programming: Program Design Including Data Structures
24
Generic 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 & Java Programming: Program Design Including Data Structures
25
Generic 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 Java Programming: Program Design Including Data Structures
26
Array-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 Java Programming: Program Design Including Data Structures
27
Array-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 Java Programming: Program Design Including Data Structures
28
Array-Based Lists (continued)
Figure 15-1 UML class diagram of the interface ArrayListADT Java Programming: Program Design Including Data Structures
29
Array-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 Initially the size of the array is larger than the size of the list At a larger stage, the list can grow to a larger size We must know how full the array is Java Programming: Program Design Including Data Structures
30
Array-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 Java Programming: Program Design Including Data Structures
31
The class ArrayListClass
Implements 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 Java Programming: Program Design Including Data Structures
32
The class ArrayListClass (continued)
Figure 15-2 UML class diagram of the class ArrayListClass Java Programming: Program Design Including Data Structures
33
The class ArrayListClass (continued)
Definition of this class public abstract class ArrayListClass<T> implements ArrayListADT<T>, 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 } Java Programming: Program Design Including Data Structures
34
The class ArrayListClass (continued)
Constructor public ArrayListClass(int size) { if (size <= 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 Object[maxSize]; Java Programming: Program Design Including Data Structures
35
The class ArrayListClass (continued)
Method removeAt public void removeAt(int location) { if (location < 0 || location >= length) System.err.println("The location of the item to " + "be removed is out of range."); else for (int i = location; i < length - 1; i++) list[i] = list[i + 1]; list[length - 1] = null; length--; } } //end removeAt Java Programming: Program Design Including Data Structures
36
The class ArrayListClass (continued)
Method retrieveAt public T retrieveAt(int location) { if (location < 0 || location >= length) System.err.println("The location of the item to be " + "retrieved is out of range."); return null; } else return list[location]; } //end retrieveAt Java Programming: Program Design Including Data Structures
37
Unordered Lists Figure 15-4 UML class diagram of the class UnorderedArrayList and the inheritance hierarchy Java Programming: Program Design Including Data Structures
38
Unordered Lists (continued)
Definition of this class public class UnorderedArrayList<T> extends ArrayListClass<T> { //Place the definitions of the methods and the //constructors here. } Java Programming: Program Design Including Data Structures
39
Unordered Lists (continued)
Constructors //Default constructor public UnorderedArrayList() { super(); } //Constructor with a parameter public UnorderedArrayList(int size) super(size); Java Programming: Program Design Including Data Structures
40
Unordered Lists (continued)
Method insertAt public void insertAt(int location, T insertItem) { if (location < 0 || location >= maxSize) System.err.println("The position of the item to " + "be inserted is out of range."); else if (length >= maxSize) //list is full System.err.println("Cannot insert in a full list."); else for (int i = length; i > location; i--) list[i] = list[i - 1]; //move the elements down list[location] = insertItem; length++; //increment the length } } //end insertAt Java Programming: Program Design Including Data Structures
41
Unordered Lists (continued)
Method seqSearch public int seqSearch(T searchItem) { int loc; boolean found = false; for (loc = 0; loc < length; loc++) if (list[loc].equals(searchItem)) found = true; break; } if (found) return loc; else return -1; } //end seqSearch Java Programming: Program Design Including Data Structures
42
Unordered 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); System.out.println("The item to be deleted " + "is not in the list."); } } //end remove Java Programming: Program Design Including Data Structures
43
Ordered List Figure 15-4 UML class diagram of the class OrderedArrayList and the inheritance hierarchy Java Programming: Program Design Including Data Structures
44
Ordered List (continued)
Class definition public class OrderedArrayList <T> extends ArrayListClass<T> { // Place constructor and method definitions // here. } Java Programming: Program Design Including Data Structures
45
Ordered List (continued)
Constructors //Default constructor public OrderedArrayList() { super(); } //Constructor with a parameter public OrderedArrayList(int size) super(size); Java Programming: Program Design Including Data Structures
46
Ordered List (continued)
Method seqSearch public int seqSearch(T searchItem) { int loc; boolean found = false; for (loc = 0; loc < length; loc++) Comparable<T> temp = (Comparable<T>) list[loc]; if (temp.compareTo(searchItem) >= 0) found = true; break; } Java Programming: Program Design Including Data Structures
47
Ordered List (continued)
Method seqSearch (continued) if (found) { if (list[loc].equals(searchItem)) return loc; else return -1; } } //end seqSearch Java Programming: Program Design Including Data Structures
48
Ordered List (continued)
Method insert public void insert(T insertItem) { int loc; boolean found = false; if (length == 0) //list is empty list[length++] = insertItem; //insert insertItem //and increment length else if (length == maxSize) System.err.println("Cannot insert in a full list."); Java Programming: Program Design Including Data Structures
49
Ordered List (continued)
Method insert (continued) else { for (loc = 0; loc < length; loc++) Comparable<T> temp = (Comparable<T>) list[loc]; if (temp.compareTo(insertItem) >= 0) found = true; break; } for (int i = length; i > loc; i--) list[i] = list[i - 1]; //move the elements down list[loc] = insertItem; //insert insertItem length++; //increment the length } //end insert Java Programming: Program Design Including Data Structures
50
Programming 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 Java Programming: Program Design Including Data Structures
51
Chapter Summary Cloneable interface Comparable 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 Java Programming: Program Design Including Data Structures
52
Chapter 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 Java Programming: Program Design Including Data Structures
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.