Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 15: Generic Methods, Classes, and Array-Based Lists Java Programming: Program Design Including Data Structures Program Design Including Data Structures."— Presentation transcript:

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

2 Java Programming: Program Design Including Data Structures2 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

3 Java Programming: Program Design Including Data Structures3 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

4 Java Programming: Program Design Including Data Structures4 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

5 Java Programming: Program Design Including Data Structures5 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

6 Java Programming: Program Design Including Data Structures6 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; }

7 Java Programming: Program Design Including Data Structures7 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; }

8 Java Programming: Program Design Including Data Structures8 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

9 Java Programming: Program Design Including Data Structures9 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; }

10 Java Programming: Program Design Including Data Structures10 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); }

11 Java Programming: Program Design Including Data Structures11 The interface Comparable (continued)  If a class implements multiple interfaces  Separate all interfaces names using commas  Example public class Clock implements Cloneable, Comparable

12 Java Programming: Program Design Including Data Structures12 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; }

13 Java Programming: Program Design Including Data Structures13 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; }

14 Java Programming: Program Design Including Data Structures14 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); if (retValue == 0) retValue = bDay.compareTo(temp.bDay); return retValue; }

15 Java Programming: Program Design Including Data Structures15 Generic Methods  Consider the following three methods: public static void print(int... list) { for (int elem : list) System.out.print(elem + " "); System.out.println(); }

16 Java Programming: Program Design Including Data Structures16 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) System.out.print(elem + " "); System.out.println(); }

17 Java Programming: Program Design Including Data Structures17 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

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

19 Java Programming: Program Design Including Data Structures19 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

20 Java Programming: Program Design Including Data Structures20 Generic Methods (continued)  Generic definition of the method print public static void print(T... list) //Line 1 { for (T elem : list) //Line 2 System.out.print(elem + " "); //Line 3 System.out.println(); //Line 4 }

21 Java Programming: Program Design Including Data Structures21 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);

22 Java Programming: Program Design Including Data Structures22 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

23 Java Programming: Program Design Including Data Structures23 Generic Methods and Bounded Type Parameters (continued)  Definition of a generic method larger public static > T larger(T x, T y) { if (x.compareTo(y) >= 0) return x; else return y; }

24 Java Programming: Program Design Including Data Structures24 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 &

25 Java Programming: Program Design Including Data Structures25 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

26 Java Programming: Program Design Including Data Structures26 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

27 Java Programming: Program Design Including Data Structures27 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

28 Java Programming: Program Design Including Data Structures28 Array-Based Lists (continued) Figure 15-1 UML class diagram of the interface ArrayListADT

29 Java Programming: Program Design Including Data Structures29 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

30 Java Programming: Program Design Including Data Structures30 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

31 Java Programming: Program Design Including Data Structures31 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

32 Java Programming: Program Design Including Data Structures32 The class ArrayListClass (continued) Figure 15-2 UML class diagram of the class ArrayListClass

33 Java Programming: Program Design Including Data Structures33 The class ArrayListClass (continued)  Definition of this class public abstract class ArrayListClass implements ArrayListADT, 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 }

34 Java Programming: Program Design Including Data Structures34 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]; }

35 Java Programming: Program Design Including Data Structures35 The class ArrayListClass (continued)  Method removeAt public void removeAt(int location) { if (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

36 Java Programming: Program Design Including Data Structures36 The class ArrayListClass (continued)  Method retrieveAt public T retrieveAt(int location) { if (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

37 Java Programming: Program Design Including Data Structures37 Unordered Lists Figure 15-4 UML class diagram of the class UnorderedArrayList and the inheritance hierarchy

38 Java Programming: Program Design Including Data Structures38 Unordered Lists (continued)  Definition of this class public class UnorderedArrayList extends ArrayListClass { //Place the definitions of the methods and the //constructors here. }

39 Java Programming: Program Design Including Data Structures39 Unordered Lists (continued)  Constructors //Default constructor public UnorderedArrayList() { super(); } //Constructor with a parameter public UnorderedArrayList(int size) { super(size); }

40 Java Programming: Program Design Including Data Structures40 Unordered Lists (continued)  Method insertAt public void insertAt(int location, T insertItem) { if (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

41 Java Programming: Program Design Including Data Structures41 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

42 Java Programming: Program Design Including Data Structures42 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); else System.out.println("The item to be deleted " + "is not in the list."); } } //end remove

43 Java Programming: Program Design Including Data Structures43 Ordered List Figure 15-4 UML class diagram of the class OrderedArrayList and the inheritance hierarchy

44 Java Programming: Program Design Including Data Structures44 Ordered List (continued)  Class definition public class OrderedArrayList extends ArrayListClass { // Place constructor and method definitions // here. }

45 Java Programming: Program Design Including Data Structures45 Ordered List (continued)  Constructors //Default constructor public OrderedArrayList() { super(); } //Constructor with a parameter public OrderedArrayList(int size) { super(size); }

46 Java Programming: Program Design Including Data Structures46 Ordered List (continued)  Method seqSearch public int seqSearch(T searchItem) { int loc; boolean found = false; for (loc = 0; loc < length; loc++) { Comparable temp = (Comparable ) list[loc]; if (temp.compareTo(searchItem) >= 0) { found = true; break; }

47 Java Programming: Program Design Including Data Structures47 Ordered List (continued)  Method seqSearch (continued) if (found) { if (list[loc].equals(searchItem)) return loc; else return -1; } else return -1; } //end seqSearch

48 Java Programming: Program Design Including Data Structures48 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.");

49 Java Programming: Program Design Including Data Structures49 Ordered List (continued)  Method insert (continued) else { for (loc = 0; loc < length; loc++) { Comparable temp = (Comparable ) 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

50 Java Programming: Program Design Including Data Structures50 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

51 Java Programming: Program Design Including Data Structures51 Chapter 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

52 Java Programming: Program Design Including Data Structures52 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


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

Similar presentations


Ads by Google