1 / 69

Generics

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

kyrie
Download Presentation

Generics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 clonemethod • 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 classObject 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 classto provide an appropriate definition of the method compareTo • Values of two objects of that classcan be properly compared • Allows ordering objects • compareToreturns 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 intcompareTo(Object otherClock) { Clock temp = (Clock) otherClock; inthrDiff = hr - temp.hr; if (hrDiff != 0) return hrDiff; intminDiff = 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 intcompareTo(Object otherDate) { Date temp = (Date) otherDate; intyearDiff = year - temp.year; if (yearDiff != 0) return yearDiff; intmonthDiff = month - temp.month; if (monthDiff != 0) return monthDiff; return day - temp.day; }

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

  18. Example: method compareTo() in class PersonalInfo: public intcompareTo(Object other) { PersonalInfo temp = (PersonalInfo) other; intcompare = 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. • http://download.oracle.com/javase/6/docs/api/

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

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

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

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

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

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

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

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

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

  30. 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!

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

  32. 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 (inti = 0;i < list.length; i++) //Line 2 System.out.print(list[i] + " "); //Line 3 System.out.println(); //Line 4 } Java Programming: Program Design Including Data Structures

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

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

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

  36. Generic Methods and Bounded Type Parameters (continued) //findMax/arraypublic static <T extends Comparable<T> > T findMax (T[] list) { intmaxIndex = 0; for(inti = 1; i < list.length; i++) if(list[i].compareTo(list[maxIndex]) > 0)maxIndex= i; return list[maxIndex];} Java Programming: Program Design Including Data Structures

  37. Generic Methods and Bounded Type Parameters (continued) //bubble sortpublic static <T extends Comparable<T>> void bubbleSort (T[] list) { for (int pass = 0; pass < length - 1; pass++) { for (inti = 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

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

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

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

  41. 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 ArrayListinstead • 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.

  42. 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>();

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

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

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

  46. Lists vsarrays • 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

  47. Java arrays and ArrayList • ArrayList is a Java class rather than a special data type in the language. • Arrays can’t grow. ArrayListgrows and shrinks as needed at execution time • No need to keep track of the number of elements, ArrayListhas 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

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

More Related