Chapter 15 Generic Methods Classes and ArrayBased Lists

Chapter 15: Generic Methods, Classes, and Array-Based Lists Java Programming: Program Design Including Data Structures

Chapter Objectives s Learn about the interfaces Cloneable and Comparable and how to implement them s Learn about generic methods and classes s Learn how to implement generic array-based lists s Explore how various operations, such as search, insert, and remove, are implemented on lists Java Programming: Program Design Including Data Structures 2

The method, clone() s Method clone of the class Object s Protected method inherited by every class in Java s Cannot be invoked by an object outside the definition of its class s Provides a bit-by-bit copy of the object’s data in storage s Provides a shallow copy of object’s data s Appropriate definition of the method clone with deep copy redefine, override!!! s To make a deep copy of an object’s data, its class must override the clone method Java Programming: Program Design Including Data Structures 3

The interface cloneable s The interface Cloneable has no method headings that need to be implemented s But, classes that implement this interface must only redefine the clone method s Shallow copies work only when the cloned objects contain only primitive type data or data of immutable objects such as Integer or String Java Programming: Program Design Including Data Structures 4

The interface cloneable (continued) s Writing the clone method s First, invoke the clone method of the super class s Note that the clone method returns a reference of the Object type s Then, change the values of instance variables of mutable types s The method clone of the class Object throws Clone. Not. Supported. Exception Java Programming: Program Design Including Data Structures 5

clone for the class Clock, Person, and Date s Example of a clone method public Object clone() { try { return super. clone(); //Invoke the method clone of //the super class } catch (Clone. Not. Supported. Exception e) { return null; } } Java Programming: Program Design Including Data Structures 6

clone for the class Person. Info s clone method for variables of mutable types in the class Person. Info public Object clone() { try { Personal. Info copy = (Personal. Info) super. clone(); copy. b. Day = (Date) b. Day. clone(); //explicitly clone //the object b. Day copy. name = (Person) name. clone(); //explicitly clone //the object name return copy; } catch (Clone. Not. Supported. Exception e) { return null; } Java Programming: Program Design Including Data Structures } 7

The interface Comparable s The interface Comparable has only one method heading, which is compare. To s Used to force a class to provide an appropriate definition of the method compare. To s To properly compare values of two objects of that class s Example public class Clock implements Comparable Java Programming: Program Design Including Data Structures 8

compare. To for Clock class s Writing the compare. To method for Clock public int compare. To(Object other. Clock) { Clock temp = (Clock) other. Clock; int hr. Diff = hr - temp. hr; if (hr. Diff != 0) return hr. Diff; int min. Diff = min - temp. min; if (min. Diff != 0) return min. Diff; return sec - temp. sec; } Java Programming: Program Design Including Data Structures 9

equals for Clock class s Writing the equals method for Clock s to make it compatible with the method equals of the class Object public boolean { Clock temp return (hr && && } equals(Object other. Clock) = (Clock) other. Clock; == temp. hr min == temp. min sec == temp. sec); Java Programming: Program Design Including Data Structures // type cast 10

Implementing multiple interfaces s If a class implements multiple interfaces s Separate all interfaces names using commas s Example public class Clock implements Cloneable, Comparable Java Programming: Program Design Including Data Structures 11

compare. To for Person class s Writing the compare. To method for Person public int compare. To(Object other. Person) { Person temp = (Person) other. Person; if (first. Name. equals(temp. first. Name) && last. Name. equals(temp. last. Name)) return 0; else if ((last. Name. compare. To(temp. last. Name) < 0) || ((last. Name. equals(temp. last. Name) && (first. Name. compare. To(temp. first. Name) < 0)))) return -1; else return 1; } Java Programming: Program Design Including Data Structures 12

compare. To for Date class s Writing the compare. To method for Date public int compare. To(Object other. Date) { Date temp = (Date) other. Date; int yr. Diff = d. Year - temp. d. Year; if (yr. Diff != 0) return yr. Diff; int month. Diff = d. Month - temp. d. Month; if (month. Diff != 0) return month. Diff; return d. Day - temp. d. Day; } Java Programming: Program Design Including Data Structures 13

compare. To for Person. Info class s Writing the compare. To method for Personal. Info public int compare. To(Object other) { Personal. Info temp = (Personal. Info) other; int ret. Value; ret. Value = person. ID - temp. person. ID; if (ret. Value == 0) ret. Value = name. compare. To(temp. name); if (ret. Value == 0) ret. Value = b. Day. compare. To(temp. b. Day); return ret. Value; } Java Programming: Program Design Including Data Structures 14

Generic Methods Consider the following three print() methods for three lists of int, double, and String public static void print(int. . . list){ for (int elem : list) System. out. print(elem + " "); System. out. println(); } public static void print(double for (double elem : list) System. out. print(elem + System. out. println(); } public static void print(String for (String elem : list) System. out. print(elem + System. out. println(); } . . . list){ " "); Note: foreach loop, for (datatype identifier : array. Name) { System. out. println(identifier) } Java Programming: Program Design Including Data Structures 15

Generic Methods (continued) s Definition of the method print is identical in each case s We can use Java’s mechanism of generic methods s Write only one definition rather than three different definitions s Generic methods are defined using type parameters Java Programming: Program Design Including Data Structures 16

Generic Methods (continued) s Type parameters s Identifiers that specify generic type names s Separated by commas and enclosed in angular brackets, < and > s Also known as type variables s Used to s Declare the return type of the method s Declare formal parameters s Declare local variables s Cannot represent primitive types Java Programming: Program Design Including Data Structures 17

Generic Methods (continued) s A skeleton form of a generic method is s T is referred to as the type parameter s You can declare a reference variable using the type parameter T s You cannot instantiate objects using the type parameter Java Programming: Program Design Including Data Structures 18

Generic Methods (continued) s Generic definition of the method print public static <T> void print(T. . . list) { for (T elem : list) System. out. print(elem + " "); System. out. println(); } Java Programming: Program Design Including Data Structures //Line 1 //Line 2 //Line 3 //Line 4 19
![Generic Methods (continued) s Usage example Integer[] int. List = {2, 3, 32, 56}; Generic Methods (continued) s Usage example Integer[] int. List = {2, 3, 32, 56};](http://slidetodoc.com/presentation_image_h/7b3fac60899cccaab2ae15f7bddee109/image-20.jpg)
Generic Methods (continued) s Usage example Integer[] int. List = {2, 3, 32, 56}; Double[] num. List = {14. 56, 32. 78, 11. 98}; String[] str. List = {"Java", "C++", "Basic", "Perl"}; print(int. List); print(num. List); print(str. List); Java Programming: Program Design Including Data Structures 20

Generic Methods and Bounded Type Parameters s There are situations when the type parameter T must be restricted s An example: generic method larger s Finds the larger value of two objects s Method works with built-in as well as user-defined classes s Objects are compared using compare. To s Method should work only with classes that provide a definition of this method Java Programming: Program Design Including Data Structures 21

Generic Methods and Bounded Type Parameters (continued) s Definition of a generic method larger Upper bound of the type parameter T public static <T extends Comparable<T> > T larger(T x, T y) { if (x. compare. To(y) >= 0) return x; else return y; } Note: T represents a generic type. x and y and return types of the method larger are the type T. Java Programming: Program Design Including Data Structures 22

Generic Methods and Bounded Type Parameters (continued) s Previously, we want the method larger to use the method compare. To. s When a type parameter declaration bounds a parameter Always use the keyword extends regardless of whether the type parameter extends a class or an interface s 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 23

Generic Classes s You can also define generic classes s The type parameter(s) are enclosed in angular brackets (< and >) and may be bounded or unbounded. s A typical form of a generic class is s Generic classes are used to write a single definition for a set of related classes s Also known as parametric classes Java Programming: Program Design Including Data Structures 24

Array-Based Lists s Definition of a list: s A list is a collection of elements of the same type s The length of a list is the number of elements in the list s Example s Hardware store list of items s Available items s Number of pieces in stock s Price Java Programming: Program Design Including Data Structures 25

Array-Based Lists (continued) s Common operations performed on a list s s s s s Create the list Determine whether the list is empty or full Find the size of the list Destroy, or clear, the list Determine whether an item is the same as a given list element 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 26

Array-Based Lists (continued) Figure 15 -1 UML class diagram of the interface Array. List. ADT Java Programming: Program Design Including Data Structures 27

Array-Based Lists (continued) s The list can be sorted or unsorted s However, the algorithms to implement certain operations are the same s An effective, convenient, and common way to process a list is to store it in an array s Initially the size of the array is larger than the size of the list s At a larger stage, the list can grow to a larger size s We must know how full the array is Java Programming: Program Design Including Data Structures 28

Array-Based Lists (continued) s Variables needed to maintain and process the list in an array s The array, list, holding the list elements s A variable, length, to store the length of the list s A variable, max. Size, to store the size of the array Java Programming: Program Design Including Data Structures 29

The class Array. List. Class s Implements the operations that are common for sorted and unsorted lists s It does not implement all the operations of the interface Array. List. ADT. Why? s Consider a search method for sorted and unsorted lists s Still, the class is declared abstract s We do not want to instantiate objects of this class Java Programming: Program Design Including Data Structures 30

The class Array. List. Class (continued) abstract class protected instance variables abstract methods Note: abstract class and abstract methods are shown in italics. Figure 15 -2 UML class diagram of the class Array. List. Class Java Programming: Program Design Including Data Structures 31

The class Array. List. Class (continued) protected instance variables s Definition of this class public abstract class Array. List. Class<T> implements protected Array. List. ADT<T>, Cloneable instance { variables protected int length; //to store the length of the list protected int max. Size; //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 32

The class Array. List. Class (continued) s Constructor public Array. List. Class(int size) { if (size <= 0) { System. err. println("The array size must be positive. " + "Creating an array of size 100. "); max. Size = 100; } else max. Size = size; length = 0; list = (T[]) new Object[max. Size]; } Java Programming: Program Design Including Data Structures 33

The class Array. List. Class (continued) s Method remove. At public void remove. At(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 remove. At Java Programming: Program Design Including Data Structures 34

The class Array. List. Class (continued) s Method retrieve. At public T retrieve. At(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 retrieve. At Java Programming: Program Design Including Data Structures 35

Unordered Lists Figure 15 -4 UML class diagram of the class Unordered. Array. List and the inheritance hierarchy Java Programming: Program Design Including Data Structures 36

Unordered Lists (continued) s Definition of this class public class Unordered. Array. List<T> extends Array. List. Class<T> { //Place the definitions of the methods and the //constructors here. } Java Programming: Program Design Including Data Structures 37

Unordered Lists (continued) s Constructors //Default constructor public Unordered. Array. List() { super(); } //Constructor with a parameter public Unordered. Array. List(int size) { super(size); } Java Programming: Program Design Including Data Structures 38

Unordered Lists (continued) s Method insert. At public void insert. At(int location, T insert. Item) { if (location < 0 || location >= max. Size) System. err. println("The position of the item to " + "be inserted is out of range. "); else if (length >= max. Size) //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 list[location] = insert. Item; length++; //increment the length } } //end insert. At Java Programming: Program Design Including Data Structures 39

Unordered Lists (continued) s Method seq. Search public int seq. Search(T search. Item) { int loc; boolean found = false; for (loc = 0; loc < length; loc++) if (list[loc]. equals(search. Item)) { found = true; break; } if (found) return loc; else return -1; } //end seq. Search Java Programming: Program Design Including Data Structures 40

Unordered Lists (continued) s Method remove public void remove(T remove. Item) { int loc; if (length == 0) System. err. println("Cannot delete from an " + "empty list. "); else { loc = seq. Search(remove. Item); if (loc != -1) remove. At(loc); else System. out. println("The item to be deleted " + "is not in the list. "); } } //end remove Java Programming: Program Design Including Data Structures 41

Ordered List Figure 15 -4 UML class diagram of the class Ordered. Array. List and the inheritance hierarchy Java Programming: Program Design Including Data Structures 42

Ordered List (continued) s Class definition public class Ordered. Array. List <T> extends Array. List. Class<T> { // Place constructor and method definitions // here. } Java Programming: Program Design Including Data Structures 43

Ordered List (continued) s Constructors //Default constructor public Ordered. Array. List() { super(); } //Constructor with a parameter public Ordered. Array. List(int size) { super(size); } Java Programming: Program Design Including Data Structures 44

Ordered List (continued) s Method seq. Search public int seq. Search(T search. Item) { int loc; boolean found = false; for (loc = 0; loc < length; loc++) { Comparable<T> temp = (Comparable<T>) list[loc]; if (temp. compare. To(search. Item) >= 0) { found = true; break; } } if (found) { if (list[loc]. equals(search. Item)) return loc; else return -1; } //end seq. Search Note: Since class Object does not contain the method compare. To() create a reference of the type Comparable<T> and use the compare. To() method. Java Programming: Program Design Including Data Structures 45

Ordered List (continued) s Method insert public void insert(T insert. Item) { int loc; boolean found = false; if (length == 0) //list is empty list[length++] = insert. Item; //insert. Item //and increment length else if (length == max. Size) System. err. println("Cannot insert in a full list. "); Java Programming: Program Design Including Data Structures 46

Ordered List (continued) s Method insert (continued) else { for (loc = 0; loc < length; loc++) { Comparable<T> temp = (Comparable<T>) list[loc]; if (temp. compare. To(insert. Item) >= 0) { found = true; break; } } for (int i = length; i > loc; i--) list[i] = list[i - 1]; //move the elements down list[loc] = insert. Item; //insert. Item length++; //increment the length } } //end insert Java Programming: Program Design Including Data Structures 47

Programming Example: Polynomial Operations s Write a class that implements the following basic operations performed on polynomials s s Evaluating a polynomial Adding polynomials Subtracting polynomials Multiplying polynomials Dividing polynomials Java Programming: Program Design Including Data Structures 48

Chapter Summary s Cloneable interface s clone method makes a bit-by-bit copy of the object s Classes can override this method to provide a deep copy s Comparable interface s Used to force classes to implement the compare. To method s Objects can be properly compared using the compare. To method Java Programming: Program Design Including Data Structures 49

Chapter Summary (continued) s Generic methods s Created using type parameters s Allow use of restricted type parameters s Generic classes s Array-based lists s Lists are collection of elements of the same type s Arrays provide a convenient way to implement lists s Lists can be either unsorted or sorted Java Programming: Program Design Including Data Structures 50
- Slides: 50