Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Generics.

Similar presentations


Presentation on theme: "Java Generics."— Presentation transcript:

1 Java Generics

2 Objectives Wrapper classes Describe generics
Use generic classes/methods Complex generic types Use generic interfaces Ex. Comparable More Generics Wildcards in generics Erasure

3 Readings/ Tutorials on Generics
Java Sun Other

4 Wrapper Classes String s = new String( "hello" ); Object obj;
Java variable can be one of the 8 primitive data types. Anything that's not one of the eight primitive types is a reference to an object. Java has an important built-in data type called Object. An Object variable is capable of holding a reference to any kind of object.  In Java, a variable can be declared as being of only one type. Java uses the technique of strong typing to help prevent bugs. One can convert primitive data types with casting. There are widening conversion and narrowing conversion.  String s = new String( "hello" ); Object obj; obj = s; // Widening conversion, since "Object" refers to a wider variety of things than "String“ s = new String( "world" ); s = (String) obj; // Narrowing conversion, need to use typecast

5 Wrapper Classes A wrapper class is a class in which each object holds a primitive value. Primitive Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean

6 Examples Integer i = new Integer(3); // boxing, primitive value --> wrapper object i = 4; // auto-boxing int j = i.intValue(); // un-boxing, wrapper object --> primitive value j = i; // auto-unboxing Integer i = new Integer(3); Number n = i; // widening conversion from Integer to Number Number n = new Integer(2); // widening conversion from Integer to Number Integer i = (Integer) n; // narrowing conversion from Number to Integer Number n; Integer i; n = new Integer(3); i = (Integer) n; // This is legal n = new Double(3.1415); i = (Integer) n; // This is illegal if (n instanceof Integer) n = new Double(3.1415); i = (Integer) n; // This will not be attempted

7 Advantages and Disadvantages of Wrapper Objects
The advantage of putting a value in a wrapper object is that the wrapper object is a Java object. We can create some generic class that can handle any primitive type, for example, a set of integers, a set of characters, a set of floats, etc. The disadvantage is that there might be some potential type errors that can't be caught until the program is running. For example, the programmer might accidentally use a method with an Integer set, but assign the result to a Character set. Such a mistake would compile, but at runtime there would be a ClassCastException from the illegal narrowing conversion.   Starting with 5.0, Java includes a generics framework for using abstract types in a way that avoids many explicit casts.

8 Generic Class A class that is defined with a parameter for a type is called a generic class or a parameterized class. A generic class is written by putting a generic type parameter (for example, T) in angle brackets immediately after the class name in the class's implementation. The generic type parameter (T) will eventually be an Integer, or a Character, or anything. The name can be any legal Java identifier, but it is recommended to use single capital letters such as T (abbreviation for "type") or E (abbreviation for "element"). public class Sample <T> { private T data; public void setData(T newData) { data = newData; } public T getData() { return data; } }

9 Generic Classes (Cont.)
A generic class is used like any other class, except you specify a reference type to be plugged in for the type parameter.  Ex. Sample<String> is said to instantiate the generic class Sample. Sample<String> obj = new Sample<String> (); obj.setData("Hello");

10 Generic Class Constructor
A constructor can use the type parameter, but the constructor heading does not include type parameters in angle brackets. 1 public class Pair <T> { 2 private T first; 3 private T second; 4 5 public Pair() { first = null; second = null; 8 } 9 public Pair(T firstItem, T secondItem) { first = firstItem; second = secondItem; } public String toString() { return "(" + first + ", " + second + ")"; } 16 }  Constructor headings do not include the type parameter in angular brackets Constructor can use the type parameter as arguments

11 Generic Class Constructor (Cont.)
Although the class name in a parameterized class definition has a type parameter attached, the type parameter is not used in the heading of the constructor definition: public Pair<T> () // wrong ! A constructor can use the type as the type for a parameter of the constructor, but in this case, the angular brackets are not used: public Pair(T first, T second) However, when a generic class is instantiated, the angular brackets are used: Pair<String> pair = new Pair<String> ("Happy", "Day");

12 Generic Class Definition: An Example

13 Generic Class Definition: An Example (Cont.)

14 Generic Class Usage: An Example

15 Generics Generics were introduced in JDK 1.5
Generics were added to several interfaces and classes in the Java API Benefits Generics provide the capability to parameterize types, i.e. Defining classes or methods with a generic type that can be substituted using a concrete type by the compiler. Generics enable error detection at compile time, rather than runtime. Allows the definition of allowable object types that a class or method may work with.

16 ArrayList Example java.util.Arraylist

17 (Some) methods contained in class ArrayList
Description ArrayList ( ) Constructs an empty ArrayList ArrayList (int cap) Constructs an Ar.List with initial capacity of cap boolean add(int i, Object obj) Inserts obj at position i of the ArrayList boolean add(Object obj) Add obj at the end of the ArrayList Object remove(int i) Removes and returns obj at location i boolean remove(Object obj) Removes first occurrence of obj and returns true if found boolean contains(Object obj) returns true if obj is in the ArrayList int indexOf(Object obj) returns index of first occurrence of obj boolean set(int i, Object obj) Replaces element at location i with obj Object get (int i) Returns element at location i boolean isEmpty( ) Returns true if ArrayList is empty int size( ) Returns size of ArrayList

18 Integer x = new Integer(24);
ArrayList The method add(int i, Object obj) Code: Integer x = new Integer(24); ArrayList Alist = new ArrayList(8); //ArrayList A has capacity of 8 //assume we have added five integers Alist.add(3, x); //add Integer object at location 3 Alist x 24

19 ArrayList Example Array List<String> list = new Array List<String> (); // We can only add strings to the ArrayList list list.add ( “red” ); list.add( “blue” ); …. String s = list.get(0); // no casting is needed String t = (String) list.get(0); // casting was needed prior to JDK 1.5 … list.add(7.6547); // compile error !

20 Restrictions on Generics
The type plugged in for a type parameter must always be a reference type. It cannot be one of the 8 primitive types. For example, if you want ‘Pair<int>’, you should use ‘Pair<Integer>’. However, you can use ‘Pair<Integer>’ with int values. Thanks to auto- boxing.

21 Using Generic Classes and Automatic Boxing

22 Restrictions on Generics
instanceof does not work with generics if (! (o instanceof Pair<T>)) return false; // compiling error: illegal generic type for instanceof The way Java works with Generics ends up within the compiler. At compiler time, when a generic type is instantiated, all information about the actual parameter type is removed. This process is called type erasure. For example, an instantiation of a type such as List<Employee> and List<Invoice> results at runtime in the same type, that is, its raw type List. So, we use getClass() method to find the runtime class of this object.

23 Limitations on Type Parameter Usage
You cannot use the type parameter in expressions using new to create a new object. For example, the following are illegal within the definition of a parameterized class definition with type parameter T. T object = new T(); // not allowed ! T[] a = new T[10]; // not allowed ! T[ ] a = T[ ] (new Object[ 10]) This is allowed

24 Limitations on Generic Class Instantiation
Arrays such as the following are illegal: Pair<String> [] a = new Pair<String> [10]; Although this is a reasonable thing to want to do, it is not allowed given the way that Java implements generic classes

25 Multiple Type Parameters
A generic class definition can have any number of type parameters. Multiple type parameters are listed in angular brackets just as in the single type parameter case, but are separated by commas. <E1, E2, E3>

26 Multiple Type Parameters (Cont’d)

27 Multiple Type Parameters (Cont’d)

28 Using a Generic Class with Two Type Parameters

29 Bounds for Type Parameters
Sometimes it makes sense to restrict the possible types that can be plugged in for a type parameter T. For instance, to ensure that only classes that implement the Comparable interface are plugged in for T, define a class as follows: public class Pair<T extends Comparable> "extends Comparable" serves as a bound on the type parameter T. Use the keyword extends, not keyword implements. Any attempt to plug in a type for T which does not implement the Comparable interface will result in a compiler error message.

30 Bounds for Type Parameters (Cont’d)
A bound on a type may be a class name (rather than an interface name) Then only descendent classes of the bounding class may be plugged in for the type parameters: public class ExClass<T extends Class1> A bounds expression may contain multiple interfaces and up to one class. If there is more than one type parameter, the syntax is as follows: public class Two<T1 extends Class1, T2 extends Class2 & Comparable>

31 Generic Interfaces An interface can have one or more type parameters.
The details and notation are the same as they are for classes with type parameters.

32 Generic Class Summary To write generic classes, declare your type variables by enclosing a comma-separated list of their names within angle brackets after the name of the class or interface. You can use those type variables anywhere a type is required in any instance fields or methods of the class. However, these type variables exist only at compile time. So you cannot use a type variable with the runtime operators instanceof and new.

33 Generic Methods When a generic class is defined, the type parameter can be used in the definitions of the methods for that generic class. In addition, a generic method can be defined that has its own type parameter that is not the type parameter of any class A generic method can be a member of an ordinary class or a member of a generic class that has some other type parameter. The type parameter of a generic method is local to that method, not to the class.

34 Generic Methods (Cont’d)
The type parameter must be placed (in angular brackets) after all the modifiers, and before the returned type: public static <T> T genMethod(T[] a) When one of these generic methods is invoked, the method name is prefaced with the type to be plugged in, enclosed in angular brackets String s = NonG.<String>genMethod(c);

35 Inheritance with Generic Classes
A generic class can be defined as a derived class of an ordinary class or, another generic class

36 A Derived Generic Class: An Example

37 Bounded Parameterized Types
The <E extends Number> syntax means that the type parameter of MathBox must be a subclass of the Number class We say that the type parameter is bounded new MathBox<Integer>(5); //Legal new MathBox<Double>(32.1); //Legal new MathBox<String>(“No good!”);//Illegal

38 A Derived Generic Class: An Example (Cont’d)

39 1st Naïve Try w/o Generics
void printCollection(Collection<Object> c) { for (Object e : c) { System.out.println(e); } The problem is that this new version is much less useful than the old one. The old code could be called with any kind of collection as a parameter. The new code only takes Collection<Object>, which, as is not a super-type of all kinds of collections!

40 Correct way – Use Wildcards
So what is the supertype of all kinds of collections? Pronounced “collection of unknown” and denoted Collection<?>, A collection whose element type matches anything. It’s called a wildcard type for obvious reasons. void printCollection(Collection<?> c) { for (Object e : c) { System.out.println(e); }

41 Using Wildcards Again public class Census {
public static void addRegistry(Map<String, ? extends Person> registry) { ...} }... // Assuming Drivers are a subtype of Person Map<String, Driver> allDrivers = ...; Census.addRegistry(allDrivers);

42 Implementing Generics
Type erasure Compile-time type checking uses generics Compiler eliminates generics by erasing them Compile List<T> to List, T to Object, insert casts Generics Generic declarations are typechecked Generics are compiled once and for all No instantiation No “code bloat”

43 How Do Generics Affect My Code?
They don’t – except for the way you’ll code! Non-generic code can use generic libraries. For example, existing code will run unchanged with generic Collection library.

44 Erasure Erasure erases all generics type argument information at compilation phase. E.g. List<String> is converted to List E.g. String t = stringlist.iterator().next() is converted to String t = (String) stringlist.iterator().next() As part of its translation, a compiler will map every parameterized type to its type erasure.


Download ppt "Java Generics."

Similar presentations


Ads by Google