Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 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

3 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

4 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

5 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

6 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

7 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

8 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.

9 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();

10 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

11 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;

12 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

13 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)

14 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 {...}

15 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

16 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; }

17 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; }

18 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; }

19 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

20 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.

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

22 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).

23 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.

24 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

25 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.

26 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();

27 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

28 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

29 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)

30 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

31 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

32 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!

33 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

34 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

35 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

36 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

37 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

38 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

39 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 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

40 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

41 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

42 // 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.

43 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.

44 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>();

45 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

46 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).

47 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

48 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

49 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, 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

50 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.

51 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

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

53 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

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

55 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

56 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

57 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

58 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

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

60 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

61 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

62 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

63 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

64 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

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

66 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

67 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

68 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

69 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


Download ppt "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."

Similar presentations


Ads by Google