Java Generics.

Slides:



Advertisements
Similar presentations
New features in JDK 1.5 Can these new and complex features simplify Java development?
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Java Generics.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L13 (Chapter 21) Generics.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Creating Generic Classes. Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
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.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
 2006 Pearson Education, Inc. All rights reserved Generics.
CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
 2005 Pearson Education, Inc. All rights reserved Generics.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Working with arrays (we will use an array of double as example)
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.
Introduction to Generics
CIS 270—Application Development II Chapter 18-Generics.
Generic Instructor : Sarah Alodan. Problem?! Java code used to look like this: public class Courses { public static void main(String[] args) { ArrayList.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
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.
COM S 228 Generics Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff 201.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
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:
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
OOP Basics Classes & Methods (c) IDMS/SQL News
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.
 Pearson Education, Inc. All rights reserved. 1 Ch 18 Generics OBJECTIVES In this chapter you will learn:  To create generic methods that perform.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Generics and file handling Presented by: Abha Kumari Neha Pradip Vhanmane Raj Visa Rashmi Kewlani Suvrat Dixit.
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 20 Generic Classes and Methods
Generics.
Chapter 19 Generics Dr. Clincy - Lecture.
Generics.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
CS2011 Introduction to Programming I Methods (II)
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Generic Programming.
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

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: Generics! Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.

Advantages of Generics Stronger type checks at compile time: A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety.

Elimination of casts. Using no generics requires casting: List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); Using generics, require no casting: List<String> list = new ArrayList<String>(); String s = list.get(0); Try this code in DrJava interaction pane. If you add an integer (say 3) will compiler complain? > import java.util.*; > List list = new ArrayList() > list.add("hello") true > list.add(new Integer(3)) > list.get(0); > list.get(0) "hello" Try this code in DrJava interaction pane. If you add an integer (say 3) will compiler complain?

No compiler error if you add different data-type elements data-type element than one specified at the time of creating list (Strong type checking at compile time!)

Enabling programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read. E.g. a single sort method that sort an array of any type element with ordering

Generic Types A generic type is a generic class or interface that is parameterized over types. Let’s begin by examining a non-generic Box class that operates on objects of any type.  You are free to pass in whatever object you want to methods. There is no way to verify, at compile time, how the class is used. One part of the code may place an Integer in the box Another part of the code may mistakenly pass in a String, resulting in a runtime error.

A Generic Version of the Box Class A generic class is defined with the following format: class name<T1, T2, ..., Tn> { /* ... */ } type parameters (type variables) T1, T2, ..., and Tn With this change, the Box class becomes: all occurrences of Object are replaced by T

A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable. This same technique can be applied to create generic interfaces.

Type Parameter Naming Conventions The most commonly used type parameter names are: E - Element (used extensively by Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th types

Invoking and Instantiating a Generic Type Perform a generic type invocation replace T with some concrete value, such as Integer: Box<Integer> integerBox; Similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument —Integer in this case — to the Box class itself.

To instantiate this class, use the new keyword, as usual, but place <Integer> between the class name and the parenthesis: Box<Integer> integerBox = new Box<Integer>();

Programming Question Write generic class Box. Use following tester class to test. public class GenericsTester { public static void main(String args[]) Box<Integer> integerBox = new Box<Integer>(); integerBox.set(new Integer(3)); Integer n = integerBox.get(); System.out.println(n); }

Answer Box.java /** * Generic version of the Box class. * @param <T> the type of the value being boxed */ public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; } }

public class GenericsTester { public static void main(String args[]) Box<Integer> integerBox = new Box<Integer>(); integerBox.set(new Integer(3)); Integer n = integerBox.get(); System.out.println(n); }

Multiple Type Parameters Generic class can have multiple type parameters. E.g., the generic OrderedPair class, which implements the generic Pair interface:

The following statements create two instantiations of the OrderedPair class: Due to autoboxing, it is valid to pass a String and an int to the class. Above statements can be shortened using diamond notation: To create a generic interface, follow the same conventions as for creating a generic class.

Programming Question Create Pair interface and OrderedPair generic class that implement it. Then modify GenericsTester to create two ordered pair objects (as given in example) and print keys and values of both pairs.

Answer Pair.java OrderedPair.java public interface Pair<K, V> { public K getKey(); public V getValue(); } Pair.java OrderedPair.java public class OrderedPair<K, V> implements Pair<K, V> { private K key; private V value; public OrderedPair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; }

GenericsTester.java public class GenericsTester { public static void main(String args[]) Pair<String, Integer> p1 = new OrderedPair<String, Integer>("Even", 8); Pair<String, String> p2 = new OrderedPair<String, String>("hello", "world"); System.out.println("p1 key:"+p1.getKey()+" p1 value:"+p1.getValue()); System.out.println("p2 key:"+p2.getKey()+" p2 value:"+p2.getValue()); }

Parameterized Types You can also substitute a type parameter (i.e., K or V) with a parameterized type (i.e., List<String>). For example, using the OrderedPair<K, V> example:

Raw Types A raw type is the name of a generic class or interface without any type arguments. To create a parameterized type of Box<T>: you supply an actual type argument for the formal type parameter T: Box<Integer> intBox = new Box<>(); To create a raw type of Box<T>: Omit actual type argument Box rawBox = new Box();

Raw types show up in legacy code because lots of API classes (such as the Collections classes) were not generic prior to JDK 5.0. Read more: http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html

Generic Methods Methods that introduce their own type parameters. type parameter's scope is limited to the method The Util class includes a generic method, compare, which compares two Pair objects:

The complete syntax for invoking this method would be: Generally, type can be left out and the compiler will infer the type (type inference):

Programming Question Modify the GenericsTester to implement a generic method printArray. The method should accept an array of a generic type (E or T) and print all array elements. Find code template next slide

public class GenericsTester { public static void main(String args[]) // Create arrays of Integer, Double and Character Integer[] intArray = { 1, 4, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println( "Array integerArray contains:" ); printArray( intArray ); // pass an Integer array System.out.println( "\nArray doubleArray contains:" ); printArray( doubleArray ); // pass a Double array System.out.println( "\nArray characterArray contains:" ); printArray( charArray ); // pass a Character array } //TODO: generic method printArray

Answer public class GenericsTester { public static void main(String args[]) // Create arrays of Integer, Double and Character Integer[] intArray = { 1, 4, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println( "Array integerArray contains:" ); printArray( intArray ); // pass an Integer array System.out.println( "\nArray doubleArray contains:" ); printArray( doubleArray ); // pass a Double array System.out.println( "\nArray characterArray contains:" ); printArray( charArray ); // pass a Character array } // generic method printArray public static < E > void printArray( E[] inputArray ) // Display array elements for ( E element : inputArray ){ System.out.printf( "%s ", element ); System.out.println();

Bounded Type Parameters Sometimes you want to restrict the kinds of types that are allowed to be passed to a type parameter.  E.g., a method that operates on numbers might only want to accept instances of Number or its subclasses. Solution: use bounded type parameters ! To declare a bounded type parameter: list the type parameter's name, followed by the extends keyword, followed by its upper bound.

Example public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) T max = x; // assume x is initially the largest if ( y.compareTo( max ) > 0 ){ max = y; // y is the largest so far} if ( z.compareTo( max ) > 0 ){ max = z; // z is the largest now} return max; // returns the largest object } public static void main( String args[] ) System.out.printf( "Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ) ); System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) ); System.out.printf( "Max of %s, %s and %s is %s\n","pear", "apple", "orange", maximum( "pear", "apple", "orange" ) );

Programming Question Modify class GenericsTester to implement generics version of selection sort method. Then call this on an Integer and a Double Array. Non-generic version: public static int[] sort(int[] a) { int N = a.length; for (int i = 0; i < N; i++) int min = i; for (int j = i+1; j < N; j++) if ((a[j]<a[min]) { min = j; } } int temp = a[i]; a[i]= a[min]; a[min]=temp; return a; Find code template next slide

public class SelectionSorter { //TODO: generic selection sort method public static void main(String args[]) Integer[] intArray = {1,30,20, 10, 3}; intArray = sort(intArray); for(int n: intArray) System.out.print(" "+ n); }

Answer public class SelectionSorter { public static <T extends Comparable<T>> T[] sort(T[] a) int N = a.length; for (int i = 0; i < N; i++) int min = i; for (int j = i+1; j < N; j++) if ((a[j].compareTo(a[min]))<0) { min = j; } } T temp = a[i]; a[i]= a[min]; a[min]=temp; return a; public static void main(String args[]) Integer[] intArray = {1,30,20, 10, 3}; intArray = sort(intArray); for(int n: intArray) System.out.print(" "+ n);

Read more: http://docs.oracle.com/javase/tutorial/java/generics/