Java Generics.

Slides:



Advertisements
Similar presentations
Generics and the ArrayList Class
Advertisements

Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 23 : Generics King Fahd University of Petroleum & Minerals College of Computer Science.
Generics and The ArrayList Class
Generic programming in Java
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Java Generics.
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
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.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
ArrayList, Multidimensional Arrays
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.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Types in programming languages1 What are types, and why do we need them?
Introduction to Generics
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
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.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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:
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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 –
(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 GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Java Generics.
Sixth Lecture ArrayList Abstract Class and Interface
Java Primer 1: Types, Classes and Operators
Chapter 20 Generic Classes and Methods
Java Generics Lecture 14 CS2110 – Fall 2016
COP 3503 FALL 2012 Shayan Javed Lecture 8
Generics, Lambdas, Reflections
Generics.
Chapter 19 Generics Dr. Clincy - Lecture.
CMSC 202 Generics.
Generics (Parametric Polymorphism)
Java Programming Language
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Polymorphism.
Generics 27-Nov-18.
Generics.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Comp 249 Programming Methodology
Grouped Data Arrays, and Array Lists.
ArrayLists 22-Feb-19.
CMSC 202 Generics.
Generics, Lambdas, Reflections
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Review: libraries and packages
Winter 2019 CMPE212 5/3/2019 CMPE212 – Reminders
Generics 2-May-19.
Chapter 21 Generics.
Chapter 19 Generics.
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
Chapter 19 Generics.
Presentation transcript:

Java Generics

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

Readings/ Tutorials on Generics Java Sun http://docs.oracle.com/javase/tutorial/java/generics/index.html http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf Other http://www.javacodegeeks.com/2011/04/java-generics-quick-tutorial.html http://www.stanford.edu/class/cs242/slides/2004/java.ppt http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf http://www.lips.dist.unige.it/corsi/lsp1/dispense/LSP1-Succi-3.ppt

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

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

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

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.

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

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");

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() { 6 first = null; 7 second = null; 8 } 9 public Pair(T firstItem, T secondItem) { 10 first = firstItem; 11 second = secondItem; 12 } 13 public String toString() { 14 return "(" + first + ", " + second + ")"; 15 } 16 }  Constructor headings do not include the type parameter in angular brackets Constructor can use the type parameter as arguments

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");

Generic Class Definition: An Example

Generic Class Definition: An Example (Cont.)

Generic Class Usage: An Example

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.

ArrayList Example java.util.Arraylist

(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

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 0 1 2 3 4 5 6 7 x 24

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 !

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.

Using Generic Classes and Automatic Boxing

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.

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

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

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>

Multiple Type Parameters (Cont’d)

Multiple Type Parameters (Cont’d)

Using a Generic Class with Two Type Parameters

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.

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>

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.

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.

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.

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

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

A Derived Generic Class: An Example

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

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

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!

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

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

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” …

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.

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.