ADSA: Generics/2 1 241-423 Advanced Data Structures and Algorithms Objective –to describe basic forms of generic classes, interfaces, and methods for searching.

Slides:



Advertisements
Similar presentations
CSE Lecture 3 – Algorithms I
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Generic programming in Java
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Generics OOP Tirgul What is it good for ? Stack myStack = new Stack() ; // old version (1.4.2) myStack.push(new Integer(0)) ; int x = ((Integer)
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Main Index Contents 11 Main Index Contents Selection Sort Selection SortSelection Sort Selection Sort (3 slides) Selection Sort Alg. Selection Sort Alg.Selection.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Sort, Search, and Running Time.
1 Divide and Conquer Binary Search Mergesort Recurrence Relations CSE Lecture 4 – Algorithms II.
Chapter 8 ARRAYS Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
ADSA: Subtypes/ Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce.
Containers Overview and Class Vector
1 Sorting Algorithms (Basic) Search Algorithms BinaryInterpolation Big-O Notation Complexity Sorting, Searching, Recursion Intro to Algorithms Selection.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Chapter 9 Searching and Sorting
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
CSE 143 Lecture 15 Binary Search; Comparable reading: 13.2; 10.2 slides created by Marty Stepp
Sorting and Searching Pepper. Common Collection and Array Actions Sort in a certain order ◦ Max ◦ Min Shuffle Search ◦ Sequential (contains) ◦ Binary.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
ADSA: IntroAlgs/ Advanced Data Structures and Algorithms Objective –introduce algorithm design using basic searching and sorting, and remind.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
1 Advanced Polymorphism Polymorphism Review Comparator Interface Sorting with Comparators Selection Sort Insertion Sort.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
Comparison-Based Sorting & Analysis Smt Genap
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
Introduction to Analysis of Algorithms CS342 S2004.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Contest Algorithms January 2016 Pseudo-code for divide and conquer, and three examples (binary exponentiation, binary search, and mergesort). 5. Divide.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Composition When one class contains an instance variable whose type is another class, this is called composition. Instead of inheritance, which is based.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 4 Introduction.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
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.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
CSC 222: Object-Oriented Programming
Generics.
Generic Classes and Methods
Data Structures for Java William H. Ford William R. Topp
Chapter 11 Inheritance and Polymorphism Part 2
Podcast Ch22a Title: Array-based Binary Trees
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
Presentation transcript:

ADSA: Generics/ Advanced Data Structures and Algorithms Objective –to describe basic forms of generic classes, interfaces, and methods for searching and sorting Semester 2, Generic Classes and Methods

ADSA: Generics/2 2 Contents 1. The Object Superclass 2. Generalizing Sequential Search 3. General Collections 4. Better Collections with Generics 5. Generic Interfaces 6. The Comparable Interface 7. Generic Methods 8. Generic Searching / Sorting

ADSA: Generics/ The Object Superclass Every class is a subclass (or sub-subclass, sub-sub-subclass, etc) of the Object class.

ADSA: Generics/2 4 Object Class Methods Boolean equals(Object obj) –is obj “equal to” this object? String toString() –returns a string representation of this object Object o = new Object(); o.equals(obj); String s = o.toString();

ADSA: Generics/ Generalizing Sequential Search Our seqSearch() method from Part (1) can only search int[] arrays for an integer target –the code is shown again on the next slide A generalized version uses an Object array and an Object target –see slide 7

ADSA: Generics/2 6 Sequential Search with int public static int seqSearch(int[] arr, int first, int last, int target) { // scan elements in the range // first <= i < last; test for a match for (int i = first; i < last; i++) if (arr[i] == target) return i; // match not found return -1; }

ADSA: Generics/2 7 Sequential Search with Object public static int seqSearch(Object[] arr, int first, int last, Object target) { // scan elements in the range // first <= i < last; test for a match for (int i = first; i < last; i++) if (arr[i].equals(target)) return i; // match not found return -1; } continued

ADSA: Generics/2 8 This generalized search method can deal with arrays of any subclass (or sub-subclass, etc) of Object –now seqSearch() can search polymorphic data structures Object[] arr = new Object[3]; arr[0] = new Date(); arr[1] = new HourlyEmployee("andrew"); arr[2] = new Integer(4); seqSearch(arr, 0, 3, new Integer(3) );

ADSA: Generics/ General Collections A general-purpose collection class stores different kinds of elements. One way to implement the collection is to store the elements as Object instances. Problems: –A cast is required to access an element; –Accessing an element with the wrong cast will often cause a runtime error

ADSA: Generics/2 10 Object-based Store Example public class Store { private Object value; // data public Store () { value = null; } public Object getValue() { return value; } // set v as the new stored value public void setValue(Object v) { value = v; } public String toString() { return "value = " + value; } }

ADSA: Generics/2 11 Using the Store Store s1 = new Store(); s1.setValue("hello"); String msg1 = (String) s1.getValue(); Store s2 = new Store(); s2.setValue( new Time24() ); Time24 t2 = (Time24) s2.getValue(); String msg2 = s2.getValue(); //? Time24 t1 = (Time24) s1.getValue(); causes a runtime error

ADSA: Generics/ Better Collections with Generics In a generic collection, instances use a generic type T, which is fixed at compile- time to be a particular class. No cast is required when accessing a collection element –no possibility of runtime errors –any errors are caught at compile time, which means they can be fixed easily

ADSA: Generics/2 13 Generic Store Example public class Store { private T value; // data of type/class T public Store () { value = null; } // return the stored value as type T public T getValue() { return value; } // update the stored value public void setValue(T v) { value = v; } public String toString() { return "Value = " + value; } } All these T's must be the same class/type when a Store object is used.

ADSA: Generics/2 14 Using the Store Store ss = new Store (); ss.setValue("hello"); String msg = ss.getValue(); Store st = new Store (); st.setValue( new Time24() ); Time24 t = st.getValue(); String msg2 = st.getValue(); // warning Time24 t1 = ss.getValue(); causes a compile time error

ADSA: Generics/ Generic Interfaces Interfaces can use generic types: public interface Accumulator { public void add(T v); } Using the interface: public class Foo implements Accumulator

ADSA: Generics/2 16 AccumulatorTime Class public class AccumulatorTime implements Accumulator { private Time24 total; // time total public AccumulatorTime () { total = new Time24(); } // time is 0:00 public Time24 getTotal() { return total; } // add time v to total public void add(Time24 v) { total.addTime(v.getHour()*60 + v.getMinute()); } } store a Time24 total

ADSA: Generics/2 17 AccumulatorNumber Class public class AccumulatorNumber implements Accumulator { private double total; public AccumulatorNumber () { total = 0.0; } public double getTotal() { return total; } // add v to total as a double public void add(Number v) { total = total + v.doubleValue(); } } store a Number total

ADSA: Generics/2 18 Using the Accumulators import ds.time.Time24; public class UsingAccumlators { public static void main (String[] args) { Integer[] intArr = {7, 1, 9, 3, 8, 4}; String[] strArr = {"3:45", "2:30", "5:00"}; AccumulatorNumber accNumber = new AccumulatorNumber(); AccumulatorTime accTime = new AccumulatorTime(); :

ADSA: Generics/2 19 for (int i = 0; i < intArr.length; i++) accNumber.add(intArr[i]); System.out.println("Numeric total is " + accNumber.getTotal()); for (int i = 0; i < strArr.length; i++) accTime.add(Time24.parseTime(strArr[i])); System.out.println("Time total is " + accTime.getTotal()); } Numeric total is 32 Time total is 11:15

ADSA: Generics/ The Comparable Interface The Comparable interface is a standard way to compare objects. The interface defines a single method: public interface Comparable { int compareTo(T item); }

ADSA: Generics/2 21 compareTo() Meaning compareTo() should return an integer that is negative, 0, or positive. Meaning: –obj.compareTo(item) < 0 when obj < item –obj.compareTo(item) == 0 when obj == item –obj.compareTo(item) > 0 when obj > item

ADSA: Generics/2 22 Time24 Class with Comparable public class Time24 implements Comparable {... public int compareTo(Time24 item) //compares times { int time = hour*60 + minute; // use minutes int ttime = item.hour*60 + item.minute; // compare, returning -1, 0, or 1 if (time < ttime) return -1; else if (time == ttime) return 0; else return 1; }

ADSA: Generics/ Generic Methods A generic method includes a generic type modifier : public static T max(T a, T b) /* compare two objects of the same type/class, return the biggest */ {... } continued

ADSA: Generics/2 24 The modifier tells the compiler that T is a generic type, and the compiler checks that objects a and b and the return type are all the same. There's no need for if the method is inside a generic class, such as setValue() on slide 13.

ADSA: Generics/2 25 A Bad Generic max() javac prints an "unchecked cast" warning because this method is not type-safe –the code may cause a run-time error because a's class may not implement Comparable when object a is cast at run time public static T max(T a, T b) { if (((Comparable )a).compareTo(b) > 0) return a; else return b; } the compiler cannot be sure that the typing is correct

ADSA: Generics/2 26 // Rectangle does not implement // Comparable Rectangle rectA = new Rectangle(4,5); Rectangle rectB = new Rectangle(6,2); Rectangle r = max(rectA, rectB); // compiler time warning; // exception at runtime

ADSA: Generics/2 27 A Good Generic max() public static > T max(T a, T b) { if (a.compareTo(b) > 0) return a; else return b; } T is a bounded type The bound specifies that the generic type T must implement the Comparable interface.

ADSA: Generics/2 28 A Better Generic max() ? is a wildcard (unknown) public static > T max(T a, T b) { if (a.compareTo(b) > 0) return a; else return b; } "?" and "super" mean that T, or some superclass of T, must implement the Comparable interface.

ADSA: Generics/ Generic Searching/Sorting A generic sort method takes an array of type T. A generic search method also uses a target of type T. If the code uses compareTo() to compare objects, then the method must include the bounded wildcard modifier: >

ADSA: Generics/2 30 Generic Selection Sort public static > void selectionSort(T[] arr) { // index of smallest element in sublist int smallIndex; int idx; int n = arr.length; // idx has range 0 to n-2 for (idx = 0; idx < n-1; idx++) { // scan sublist starting at index idx smallIndex = idx; :

ADSA: Generics/2 31 // go through arr[idx+1] to arr[n-1] for (int j = idx+1; j < n; j++) /* if smaller element found, assign smallIndex to that position */ if (arr[j].compareTo(arr[smallIndex]) < 0) smallIndex = j; // swap smallest element into arr[idx] T temp = arr[idx]; arr[idx] = arr[smallIndex]; arr[smallIndex] = temp; }

ADSA: Generics/2 32 Generic binSearch () public static > int binSearch(T[] arr, int first, int last, T target) { int mid; // midpoint index T midvalue; // holds arr[mid] // save original value of last int origLast = last; // test for nonempty sublist while (first < last) { mid = (first+last)/2; midvalue = arr[mid]; :

ADSA: Generics/2 33 if (target.compareTo(midvalue) == 0) return mid; // found a match // find which sublist to search else if (target.compareTo(midvalue) < 0) // search lower sublist. set last last = mid; else // search upper sublist. set first first = mid+1; } return -1; // target not found }

ADSA: Generics/2 34 Generic Sort Examples import ds.util.Arrays; import ds.time.Time24; public class GenericSorting { public static void main (String[] args) { String[] strArr = {"red", "green", "blue"}; Integer[] intArr = {40, 70, 50, 30}; Time24[] timeArr = { new Time24(14,15), new Time24(10, 45), new Time24(22,00), new Time24(3,30)}; SalaryEmployee[] emp = { new SalaryEmployee("Dunn, Moira"," ",800), new SalaryEmployee("Garcia, Avey" " ",1200), new SalaryEmployee("Ye, Don", " ",2000)}; :

ADSA: Generics/2 35 Arrays.selectionSort(strArr); System.out.println("Sorted strings: " + Arrays.toString(strArr)); Arrays.selectionSort(intArr); System.out.println("Sorted integers: " + Arrays.toString(intArr)); Arrays.selectionSort(timeArr); System.out.println("Sorted times: " + Arrays.toString(timeArr)); Arrays.selectionSort(emp); for (int i=0; i < emp.length; i++) System.out.println(emp[i].payrollCheck()); }

ADSA: Generics/2 36 Output

ADSA: Generics/2 37 Employee and SalaryEmployee public class Employee implements Comparable { // vars are accessible by subclass methods protected String empName; : // compare social security numbers public int compareTo(Employee obj) { return empSSN.compareTo(obj.empSSN); } } continued

ADSA: Generics/2 38 public class SalaryEmployee extends Employee { // new vars private double salary; : // no compareTo() method here }