Chapter 15: Generic Methods, Classes, and Array-Based Lists

Slides:



Advertisements
Similar presentations
Java Programming: Guided Learning with Early Objects
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Dr. Liu1 Chapter 3 Array-Based Lists. Dr. Liu2 Chapter Objectives Learn about lists Explore how various operations, such as search, insert, and remove,
Data Structures Using Java1 Chapter 3 Array-Based Lists.
Generics, Lists, Interfaces
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Generics and the ArrayList Class
Generics Allow us to create a data structure regardless of the data type Generic methods and generic classes Array based lists Searching and sorting Wrapper.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Mutable, Immutable, and Cloneable Objects Chapter 15.
Chapter 8 User-Defined Classes and ADTs. Chapter Objectives Learn about classes Learn about private, protected, public, and static members of a class.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Data Structures Using Java1 Chapter 8 Search Algorithms.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 4 Linked Lists Anshuman Razdan Div of Computing Studies
Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Data Structures Using C++ 2E
16-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Interfaces, Copying/Cloning,
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Data Structures Using Java1 Chapter 8 Search Algorithms.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Applications of Arrays (Searching and Sorting) and Strings
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 8: Arrays.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Chapter 8: User-Defined Classes and ADTs
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath
Chapter 10: Class Vector and String, and Enumeration Types Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 5: ARRAYS ARRAYS. Why Do We Need Arrays? Java Programming: From Problem Analysis to Program Design, 4e 2  We want to write a Java program that.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Classes Revisited Chapter 8.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Chapter 7: Cloning and RTTI
Java Programming: Guided Learning with Early Objects
Computer Science II Exam 1 Review.
Chapter 8 Class Inheritance and Interfaces
Array-Based Lists & Pointers
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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