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.

Slides:



Advertisements
Similar presentations
Dr. Liu1 Chapter 3 Array-Based Lists. Dr. Liu2 Chapter Objectives Learn about lists Explore how various operations, such as search, insert, and remove,
Advertisements

Data Structures Using Java1 Chapter 3 Array-Based Lists.
Generics and the ArrayList Class
Chapter 15: Generic Methods, Classes, and Array-Based Lists
Generics and The ArrayList Class
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
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.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
Java Generics.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
ArrayList, Multidimensional Arrays
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.
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Introduction to Generics
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.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
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,
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
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.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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,
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
The ArrayList Data Structure Standard Arrays at High Speed!
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
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 Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
CMSC 202 ArrayList Aug 9, 2007.
Chapter 7: Cloning and RTTI
Sixth Lecture ArrayList Abstract Class and Interface
Java Programming: Guided Learning with Early Objects
Chapter 20 Generic Classes and Methods
Computer Science II Exam 1 Review.
CMSC 202 ArrayList Aug 9, 2007.
Comp 249 Programming Methodology
CMSC 202 ArrayList Aug 9, 2007.
Java Programming Language
Presentation transcript:

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 and string classes - compareTo

Copy constructor Clock c1 = new Clock(12,30,0); Clock c2 = new Clock(c1); Copy constructor Clock(final Clock otherClock) { hr = otherClock.hr; min = otherClock.min; sec = otherClock.sec; // setTime(otherClock.hr,otherClock.min,otherClock.sec); } If any of the instance variables are mutable objects need to use new

Method clone of the class Object Protected method inherited by every class But cannot be invoked by an object outside the definition of its class import java.util.*; class Testa { public static void main(String[] args) CloneEx a = new CloneEx(); CloneEx b; b = (CloneEx)a.clone(); } Error: The method clone() from the type java.lang.Object is not visible Java Programming: Program Design Including Data Structures

Method clone of the class Object Provides a bit-by-bit copy of the object’s data in storage (shallow copy) To make a deep copy of an object’s data, its class must override the clone method

The interface Cloneable Must 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

Example: public class Time implements Cloneable {...} Redefine clone() 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 Must be handled

Example of a clone method in Time, Date, Person public Object clone() { try return super.clone();//Invoke the method clone of //the super class } catch (CloneNotSupportedException e) return null; These classes only contain only simple data or immutable objects Java Programming: Program Design Including Data Structures

Note the signature of the clone method: public Object clone() This is how it is defined in the class Object You cannot have two methods in the same class with signatures that only differ by return type Until the J2SE 5.0 release, it was also true that a class could not override the return type of the methods it inherits from a superclass J2SE 5.0 allows covariant return types. What this means is that a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass. This feature removes the need for excessive type checking and casting. You may find it strange that clone returns an Object rather than explicitly returning a member of the specified class. This form of return was all that was supported in an early version of Java (that is, there was no way to have multiple methods with the same name and parameter types, but different return types), and it seems to have been retained.

Example of a clone method in Time, Date, Person clone returns a reference of the type Object or the value null --> must typecast the returned object to a reference of the same type as the class you work with Example: Time t1 = new Time(11, 12, 13); Time t2 = (Time) t1.clone();

If the class uses composition (has instance variables of type class), then the clone method has to change the values of those instance variables. Example: PersonalInfo

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();//clone //the object name return copy; } catch (CloneNotSupportedException e) return null;

The interface Comparable one method heading - compareTo forces a class to provide an appropriate definition of the method compareTo Values of two objects of that class can be properly compared Allows ordering objects compareTo returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the object passed. Java Programming: Program Design Including Data Structures

The interface Comparable equals compares only for equality Many types have the notion of a natural ordering that describes whether one value of that type is "less than" or "greater than" another: numeric values, strings (lexical/alphabetical order), times, dates, etc. Not all types have a natural ordering (ex: Point)

implements Example public class Clock implements Comparable {…} NOTE: If a class implements multiple interfaces, separate all interfaces names using commas. Example: public class Time implements Cloneable, Comparable {...}

Example: method compareTo() in class 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

Example: method compareTo() in class Date: public int compareTo(Object otherDate) { Date temp = (Date) otherDate; int yearDiff = year - temp.year; if (yearDiff != 0) return yearDiff; int monthDiff = month - temp.month; if (monthDiff != 0) return monthDiff; return day - temp.day; }

Example: method compareTo() in class Person : public int compareTo(Object otherPerson) { Person temp = (Person) otherPerson; int compare = lastName.compareTo(temp.lastName); if(compare == 0) compare = firstName.compareTo(temp.firstName); return compare; }

Example: method compareTo() in class PersonalInfo: public int compareTo(Object other) { PersonalInfo temp = (PersonalInfo) other; int compare = personID - temp.personID; if(compare == 0) compare = fullName.compareTo(temp.fullName); if(compare == 0) compare = birthDate.compareTo(temp.birthDate); return compare; }

equals Writing the equals method for Clock (to be compatible with the method equals of class Object) 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

Primitive Data Types and Wrapper Classes Wrapper Classes = Classes Integer, Double, Character, Long, Float, Boolean, etc, provided so that values of primitive data types can be treated as objects. A wrapper is an object whose sole purpose is to hold a primitive value. http://download.oracle.com/javase/6/docs/api/

Primitive type Wrapper class int Integer double Double float Float char Character boolean Boolean long Long

Reasons to use a wrapper class: As an argument of a method that expects an object (often used when manipulating collections of numbers) To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).

Integer class wraps a value of the primitive type int in an object. single instance variable whose type is int. The class provides several methods for converting an int to a String and a String to an int other methods useful when dealing with an int.

boxing and unboxing. The conversion between the primitive type and the wrapper class auto-boxing and auto-unboxing As of Java Standard Edition 5.0, Java automatically converts values back and forth between the primitive type and the corresponding wrapper class

auto-boxing: if an int is passed in a place where an Integer is required, the compiler will make a (behind the scenes) call to the wrapper class constructor (Integer) auto-unboxing: if an Integer is passed in a place where an int is required, the compiler will make a (behind the scenes) call to the intValue method. Similar behavior takes place for the 7 other primitive types/wrapper classes pairs.

Equivalent to: num = new Integer(10); x = num; //auto-unboxing Auto-boxing (of the int type) Auto-unboxing (of the Integer type) int x; Integer num; num = 10; //auto boxing Equivalent to: num = new Integer(10); x = num; //auto-unboxing Equivalent to: x = num.intValue();

When to use auto-boxing and auto-unboxing? Only when there is a mismatch between reference types and primitives Do not use for scientific computing, or other performance-sensitive numerical code. An Integer is not a perfect substitute for an int wrapper classes have limitations - cannot change the value stored in an object. Convenient, but can be confusing use with care

Generic Methods: Allows users to write reusable, generalized code Same implementation exa: Sort, search, print generic implementation to describe the basic functionality Java 5 supports generic methods and generic classes means of writing generalized code that can be used by any class in any hierarchy represented by the type parameter. Class definitions that include a type parameter are called generic types

Generic Methods- Consider the following three methods: public static void print(int ... list) { for (int elem : list) System.out.print(elem + " "); System.out.println(); } public static void print(double ... list) for (double elem : list) public static void print(String ... list) for (String elem : list)

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

Type parameters Identifiers that specify generic type names Separated by commas and enclosed in angular brackets, < and > Any non-keyword identifier can be used, uppercase letter (convention) <E> element, <T> Type Also known as type variables Java Programming: Program Design Including Data Structures

Type parameters Cannot be used anywhere a type name can be used Used to Declare the return type of the method Declare formal parameters Declare local variables Cannot represent primitive types You can declare a reference variable using the type parameter T T someObject You cannot instantiate objects using the type parameter T someObject = new T(); --> Compiling ERROR! T[] someArray = new T[SIZE]; --> Compiling ERROR!

Generic Methods (continued) A skeleton form of a generic method is T is referred to as the type parameter Java Programming: Program Design Including Data Structures

Generic Methods (continued) Generic definition(s) 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 } public static <T> void print(T[] list) //Line 1 for (int i = 0;i < list.length; i++) //Line 2 System.out.print(list[i] + " "); //Line 3 Java Programming: Program Design Including Data Structures

Calls to generic method: 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); Actual argument must be an object 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) //findMax/2 objects public static <T extends Comparable<T>> T findMax(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) //findMax/array public static <T extends Comparable<T> > T findMax (T[] list) { int maxIndex = 0; for(int i = 1; i < list.length; i++) if(list[i].compareTo(list[maxIndex]) > 0) maxIndex = i; return list[maxIndex]; } Java Programming: Program Design Including Data Structures

Generic Methods and Bounded Type Parameters (continued) //bubble sort public static <T extends Comparable<T>> void bubbleSort (T[] list) { for (int pass = 0; pass < length - 1; pass++) { for (int i = 0; i < length - 1 - i; i++) { Comparable<T> listElem = (Comparable<T>) list[i]; if (listElem.compareTo(list[i + 1]) > 0) { T temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; } } } } 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 & <T extends Comparable<T> & Cloneable> <N extends Number> Java Programming: Program Design Including Data Structures

Generic Classes used to write a single definition for a set of related classes Also known as parametric classes a generic type may have multiple type parameters each parameter must be unique within its declaring class or interface listed in angular brackets separated by commas. Java Programming: Program Design Including Data Structures

// Generic version of the Box class public class Box<T> { private T t; // T stands for "Type" public void add(T t) this.t = t; } public T get() return t; Multiple type parameters A declaration of Box<T,T>, for example, would generate an error on the second occurrence of T but Box<T,U>would be allowed.

Generic type invocation the class type plugged in for the type parameter must be specified before it can be used in a program. Box<Integer> integerBox; An instantiation of a generic class cannot be an array base type, use an ArrayList instead Like an ordinary method invocation, but instead of passing an argument to a method, you're passing a type argument — Integer in this case — to the Box class itself. parameterized type.

To instantiate this class use the new keyword, as usual, but place <Integer> between the class name and the parenthesis: integerBox = new Box<Integer>(); Or, you can put the entire statement on one line, such as: Box<Integer> integerBox = new Box<Integer>();

Type Parameter Naming Conventions By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name. The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th types

Lists Linear data structure whose components could be accessed sequentially collection of elements of the same type (homogeneous) Components of a list = List elements OR list items Head (front) = First element of the list Tail (back, end) = Last element of the list Length of a list = The number of elements in the list, varies Conceptually, there is no upper bound for length, but a computer's memory size is bounded Linear relationship --> Each element except the head has a unique predecessor, and each element except the tail has a unique successor. Unordered/unsorted list - data items are placed in no particular order; Key = attribute used to determine the logical/physical order of the list elements. Ordered/sorted list = list elements are ordered in some way -- either numerically or alphabetically or by a component (key).

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 Make a copy of the list Print 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

Lists vs arrays Advantages of lists Much easier to perform insertions and deletions (less operations). Variable size Disadvantage of using Lists over arrays Direct access of a component is impossible Use a list when the frequency of inserting and deleting elements is significantly greater than the frequency of selecting, storing or retrieving existing elements arrays are not used as much in Java as they are in most other languages

Java arrays and ArrayList ArrayList is a Java class rather than a special data type in the language. Arrays can’t grow. ArrayList grows and shrinks as needed at execution time No need to keep track of the number of elements, ArrayList has size ArrayList uses an array as a private instance variable. The base type of an ArrayList must be a class type, it cannot be a primitive type. Arrays have no methods (just length instance variable), all operations on ArrayLists are performed via method calls, many methods avail, constructor, get, set, http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html get size by calling the size method rather than by selecting a length field. An ArrayList is less efficient than an array ArrayList does not have the convenient square bracket notation

import java.util.ArrayList; Vector behaves almost exactly the same as the class ArrayList. In most situations, either class could be used, however the ArrayList class is newer (Java 5), and is becoming the preferred class.

ArrayListADT standard array behavior along with other useful operations. java.util package can hold any type of object cannot be a primitive type --> must use wrapper classes! ArrayList can change length while the program is running 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

Array-Based Lists (continued) Figure 15-1 UML class diagram of the interface ArrayListADT 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 definition 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 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 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 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 Constructors //Default constructor public OrderedArrayList() { super(); } //Constructor with a parameter public OrderedArrayList(int size) super(size); Java Programming: Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 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; } if (found) if (list[loc].equals(searchItem)) return loc; else return -1; } //end seqSearch Java Programming: Program Design Including Data Structures

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