Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMING PRACTICES Java generics.

Slides:



Advertisements
Similar presentations
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Advertisements

Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 23 : Generics King Fahd University of Petroleum & Minerals College of Computer Science.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
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.
Java 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.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Java Programming II 1 Generic Types and Inner Classes.
Java Generics.
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.
Effective Java: Generics Last Updated: Spring 2009.
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.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
 2005 Pearson Education, Inc. All rights reserved Generics.
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.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMING PRACTICES Java generics.
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
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Peyman Dodangeh Sharif University of Technology Spring 2014.
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.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
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.
 Pearson Education, Inc. All rights reserved. 1 Ch 18 Generics OBJECTIVES In this chapter you will learn:  To create generic methods that perform.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Advanced Programing practices
Java Primer 1: Types, Classes and Operators
Introducing Java Generics and Collections
Java Generics.
Chapter 20 Generic Classes and Methods
Generics, Lambdas, Reflections
Generics.
Advanced Program Design with C++
Chapter 19 Generics Dr. Clincy - Lecture.
Java Programming Language
Generics.
Generic programming in Java
Generics, Lambdas, Reflections
Advanced Programing practices
Chapter 19 Generics.
Presentation transcript:

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMING PRACTICES Java generics Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering Java Generics is a language feature that enables the definition of classes and methods that are implemented independently of some type that they use as an abstraction by accepting a type parameter. The goal is to define types and algorithms that apply in different contexts, but where the interface and general functioning and implementation can be defined such that it applies independently of the context of application. Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters. For example. a class like LinkedList is a generic type, that has a type parameter E. Instantiations, such as LinkedList or a LinkedList, are called parameterized types, and String and Integer are the respective actual type arguments. Generic programming: introduction Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering M.D. McIlroy. Mass-Produced Software Components, Proceedings of the 1st International Conference on Software Engineering, Garmisch Partenkirchen, Germany, Barbara Liskov, Alan Snyder, Russell Atkinson, and Craig Schaffert. Abstraction mechanisms in CLU. Commun. ACM 20, 8 (August 1977), doi= / Abstraction mechanisms in CLU Joseph A. Goguen. Parameterized Programming. IEEE Trans. Software Eng. 10(5) 1984.Parameterized Programming David R. Musser, Alexander A. Stepanov. Generic Programming. In International Symposium on Symbolic and Algebraic Computation (ISSAC 1988). Lecture Notes in Computer Science 358, Springer-Verlag, 1989, pp Generic Programming 1999: Sun Microsystems proposes to add generics to Java, based on GJ.GJ 2001: Sun Microsystems releases a prototype including Java Generics. 2003: Java Generics included in Java 1.5. Generics: history Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering The Java compiler uses a technique called type erasure to translate generic classes into executable code. Type erasure eliminates all generic type information at compile time. All the type information between angle brackets is thrown out so, for example, a parameterized type like List is converted into a List raw type. All remaining uses of type variables are replaced by the upper bound of the type variable (or Object if there is no type bound). Whenever the resulting code isn’t type-correct, a cast to the appropriate type is automatically inserted. Java generics: implementation Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering While Java generics syntactically look like C++ templates and are used to achieve the same purpose, it is important to note that they are not implemented using the same concepts, nor do they provide the same programming features. Java generics simply provide compile-time type safety and eliminate the need for explicit casts when using type-abstract types and algorithms. Java generics use a technique known as type erasure, and the compiler keeps track of the generic definitions internally, hence using the same class definition at compile/run time. A C++ template on the other hand use template metaprogramming, by which whenever a template is instantiated with a new type parameter, the entire code for the template is generated adapted to the type parameter and then compiled, hence having several definitions for each template instance at run time. Java generics vs. C++ templates Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering A class or method that is defined with a parameter for a type is called a generic class/method or a parameterized class/method For classes, the type parameter is included in angular brackets after the class name in the class definition heading. For methods, the type parameter is included before the method definition. Methods can define/use additional type parameters additional to their class’ type parameters. The type parameters are to be used like other types used in the definition of a class/method. When a generic class is used, the specific type to be plugged in is provided in angular brackets. When a generic method is called, its call’s parameter/return type are plugged in. Generic classes/methods: definition Joey Paquet, SOEN Advanced Programming Practices /** * Generic class that defines a wrapper class around a single * element of a generic type. */ public class Box { private T t; public void set(T t) { this.t = t; } public T get() { return t; } /** * Generic method that uses both the generic type of the class * it belongs to, as well as an additional generic type that is * bound to the Number type. */ public void inspect(){ System.out.println("T: " + t.getClass().getName()); } public void inspectWithAdditionalType(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box integerBox = new Box (); integerBox.set(new Integer(10)); integerBox.inspect(); integerBox.inspectWithAdditionalType("Hello world"); Integer i = integerBox.get(); }

Concordia University Department of Computer Science and Software Engineering When the class is compiled, type erasure is applied on the type parameter for each specific use of the generic class or method: Every occurrence of the type parameter is replaced with the highest type applicable to the type parameter. If a type bound was specified, this type is applied. If no type bound was specified, Object is used. If a value is extracted from a generic class or returned from a generic method that is of the type parameter type, its type is automatically casted to the type used at instantiation. Generic classes/methods: type erasure Joey Paquet, SOEN Advanced Programming Practices /** * Generic class that defines a wrapper class around a single * element of a generic type. */ public class Box { private Number t; public void set(Number t) { this.t = t; } public Number get() { return t; } /** * Generic method that uses both the generic type of the class * it belongs to, as well as an additional generic type that is * bound to the Number type. * */ public void inspect(){ System.out.println("T: " + t.getClass().getName()); } public void inspectWithAdditionalType(Object u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box integerBox = new Box(); integerBox.set(new Integer(10)); integerBox.inspect(); integerBox.inspectWithAdditionalType("Hello world"); Integer i = integerBox.get(); }

Concordia University Department of Computer Science and Software Engineering So, what is the difference between a generic class and a class defined using Object as the internal type? Consider a LinkedList class that can contain elements of type Object : This seems interesting, until we get the elements from the list: As the elements are of type Object, we must explicitly cast them to use them as objects of their own type after extraction. Do you see any problem with that? Generic classes: benefit Joey Paquet, SOEN Advanced Programming Practices LinkedList list = new LinkedList(); list.add("abc"); // fine list.add(new Date()); // fine as well String s = (String)list.get(0); // cast required Date d = (Date)list.get(1); // cast required

Concordia University Department of Computer Science and Software Engineering The problem is that the compiler cannot check at compile time whether such casts are valid or not. Upon execution, depending on what was actually stored as the elements of the list, the runtime system might throw a ClassCastException if the explicit casts are invalid. Using generic classes, we can define such a LinkedList and parameterize it for every specific use and ensuring type safety for each different use of the generic class: Thus, generic classes and the type erasure mechanism allow the programmer to: Define classes that are valid in different contexts of use. Ensure that they are used correctly in each specific context of use. Generic classes: benefit Joey Paquet, SOEN Advanced Programming Practices LinkedList stringList = new LinkedList (); stringList.add("Hello"); // fine // list.add(new Date(1,1)); // error String s = stringList.get(0); // no cast needed LinkedList integerList = new LinkedList (); integerList.add(new Integer(10)); // fine // integerList.add("Hello"); // error Integer i = integerList.get(0); // no cast needed

Concordia University Department of Computer Science and Software Engineering Type parameters must be class types, i.e. primitive types are not valid parameter types. The following types cannot be defined as generic: Anonymous inner classes: As their name mentions, anonymous classes do not have a name. The intent of a generic class is to define a class and then use it in different contexts. If a class does not have a name, it cannot be referred to. Exception types: Generic Java source code is translated into Java byte code through type erasure, hence loosing its generic nature at runtime. For example, MyException and MyException are in fact the same type MyException at run time. It would thus be impossible to write a type parameter to a catch clause that would catch a specific instance of a parameterized exception class. Enum types: Conceptually, an enum type and its enum values are static. Since type parameters cannot be used in any static context, the parameterization of an enum type would be pointless. Generics: restrictions Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering When defining a generic class/method, a type bound can be stated on any type parameter. A type bound can be any reference type, i.e. a class type that is used to further describe a type parameter. It restricts the set of types that can be used as type arguments and gives access to the non-static methods of the type it mentions. A type parameter can be unbounded. In this case any reference type can be used as type argument to replace the unbounded type parameter in an instantiation of a generic type. Alternatively can have one or several bounds. In this case the type argument that replaces the bounded type parameter in an instantiation of a generic type must be a subtype of all bounds. Generics: parameter type bounds Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering The syntax for specification of type parameter bounds is: i.e. a list of bounds consists of one class and/or several interfaces. The reason for imposing a type bound on a type parameter is that the code used in the implementation code of the generic class is assuming that the type used is of a certain type or any of its subtypes, or that it implements a certain interface. This can lead to rather complex class declarations such as: A pair class taking two parameters, where each parameter is of a certain type that implements Comparable with itself and implements Cloneable. The class itself implements Comparable with itself and implements Cloneable, i.e. instances of this class are Comparable with each other and are Cloneable and the same is assumed of both parts of the Pair. Generics: parameter type bounds Joey Paquet, SOEN Advanced Programming Practices class Pair & Cloneable, B extends Comparable & Cloneable > implements Comparable >, Cloneable {... }

Concordia University Department of Computer Science and Software Engineering In the add() method: The method is generic over two type parameters A and B, which must be subclasses of Number, which allows to use doubleValue(). The argument to the method is a Pair ; the type arguments to that Pair are constrained by the type parameter bounds to add(). In the swap() method: The type parameters are used to define the return type, as well as the argument. Local variables in the method are declared in terms of the type parameters. The type parameters are used as type arguments in the constructor call. Generics: parameter types, interesting cases Joey Paquet, SOEN Advanced Programming Practices class PairUtil { public static double add(Pair p) { return p.getFirst().doubleValue() + p.getSecond().doubleValue(); } public static Pair swap(Pair p) { A first = p.getFirst(); B second = p.getSecond(); return new Pair (second, first); } public class Pair { private final X a; private final Y b; public Pair(X a, Y b) { this.a = a; this.b = b; } public X getFirst() { return a; } public Y getSecond() { return b; }

Concordia University Department of Computer Science and Software Engineering A wildcard is a syntactic construct that is used to denote a family of types in a generic class/method instantiation. There are three different kinds of wildcards: " ? " : the unbounded wildcard. It stands for the family of all types. " ? extends SuperType " : a wildcard with an upper bound. It stands for the family of all types that are SuperType itself or subtypes of SuperType. " ? super SubType " - a wildcard with a lower bound. It stands for the family of all types that are SubType itself or supertypes of SubType. Java Generics: wildcards Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering The method printCollection() receives a parameter that is a Collection of elements of any type. It can do so because it does not apply any type-specific operation on the Collection it receives as a parameter. The method copy() receives as parameters two lists, where the type of elements in the source List must be a subtype of type of elements in the destination List. Failure to impose such a restriction may allow to attempt to copy the elements of a list into a list of elements of an unrelated type, leading to an illegal type cast. It must do so because it uses get() and set(), which are bound to the type of values stored in the List. Java Generics: wildcards Joey Paquet, SOEN Advanced Programming Practices public void printCollection( Collection c ){ for (Object o : c){ System.out.println(o); } public static void copy( List dest, List src) { for (int i=0; i<src.size(); i++) dest.set(i,src.get(i)); }

Concordia University Department of Computer Science and Software Engineering If a generic class is referred to without using any type parameter, it refers to a raw type, i.e. a class that has been subject to type erasure, taking the generic type’s uppermost allowable type as type argument. In this particular case, E is unbound, so a raw Basket is a Basket of Object. The class hierarchies of the parameter types are not transposed onto the generic classes that use them as parameters. Wildcards must be used in a context where they can be verified to instantiate to a specific type at runtime, e.g. new Basket () is invalid as it attempts to create a Basket containing a value of unknown type. Generic classes: instantiation vs. type parameter Joey Paquet, SOEN Advanced Programming Practices Basket b = new Basket(); // OK but using raw type! Basket b1 = new Basket (); // OK but using raw type! Basket b2 = new Basket (); // OK ! // Type mismatch: cannot convert from Basket to Basket Basket b3 = new Basket (); // WRONG !!! // Type mismatch: cannot convert from Basket to Basket Basket b4 = new Basket (); // WRONG !!! Basket b5 = new Basket (); // OK! // 1. Cannot instantiate the type Basket // 2. Type mismatch: cannot convert from Basket to Basket Basket b6 = new Basket (); // WRONG !!! class Basket {...} class Fruit {...} class Apple extends Fruit {...} class Orange extends Fruit {...}

Concordia University Department of Computer Science and Software Engineering Java generic class example: generic Pair class Joey Paquet, SOEN Advanced Programming Practices /** * Immutable generic pair class */ public class Pair { private TypeOfFirst first; private TypeOfSecond second; public Pair(){} public Pair(TypeOfFirst first, TypeOfSecond second){ this.first = first; this.second = second; } public Pair(Pair newPair){ this.first = newPair.getFirst(); this.second = newPair.getSecond(); } public TypeOfFirst getFirst() { return this.first; } public TypeOfSecond getSecond() { return this.second; } public String toString(){ return first.getClass().getName() + ":" + first.toString() + ", " + second.getClass().getName() + ":" + second.toString(); } }

Concordia University Department of Computer Science and Software Engineering Java generic class example: generic Pair class Joey Paquet, SOEN Advanced Programming Practices public class PairDriver { public static void main(String[] args) { Pair p1 = new Pair ("Hello", 1); System.out.println(p1); ArrayList v1 = new ArrayList (); for (int x = 1; x <= 3; x++) v1.add(new Integer(x)); ArrayList v2 = new ArrayList (); v2.add(new String("un")); v2.add(new String("deux")); v2.add(new String("trois")); ArrayList > v3 = new ArrayList >(); for (int x = 0; x <= 2; x++) v3.add(new Pair (v1.get(x), v2.get(x))); for (Pair p : v3) System.out.println(p); } java.lang.String:Hello, java.lang.Integer:1 java.lang.Integer:1, java.lang.String:un java.lang.Integer:2, java.lang.String:deux java.lang.Integer:3, java.lang.String:trois

Concordia University Department of Computer Science and Software Engineering Java generic class example: generic comparable Pair class Joey Paquet, SOEN Advanced Programming Practices public class ComparablePair, TypeOfSecond extends Comparable > implements Comparable > { private TypeOfFirst first; private TypeOfSecond second; public ComparablePair() {} public ComparablePair(TypeOfFirst first, TypeOfSecond second) { this.first = first; this.second = second; } public ComparablePair(ComparablePair newComparablePair) { this.first = newComparablePair.getFirst(); this.second = newComparablePair.getSecond(); } public String toString() { return first.getClass().getName() + ":" + first.toString() + ", " + second.getClass().getName() + ":" + second.toString(); } public TypeOfFirst getFirst() { return this.first; } public TypeOfSecond getSecond() { return this.second; } public int compareTo(ComparablePair otherComparablePair) { int compareFirst = first.compareTo(otherComparablePair.getFirst()); int compareSecond = second.compareTo(otherComparablePair.getSecond()); if (compareFirst != 0) { return compareFirst; } else { return compareSecond; }

Concordia University Department of Computer Science and Software Engineering Java generic class example: generic comparable Pair class Joey Paquet, SOEN Advanced Programming Practices public class ComparablePairDriver { public static void main(String[] args) { ArrayList > alcp = new ArrayList >(); alcp.add(new ComparablePair (3,"trois")); alcp.add(new ComparablePair (4,"quatre")); alcp.add(new ComparablePair (1,"un")); alcp.add(new ComparablePair (1,"one")); ComparablePair previousalcp = null; for (ComparablePair p : alcp) { System.out.println(p); if (previousalcp != null) System.out.println(p.compareTo(previousalcp)); previousalcp = new ComparablePair (p); } java.lang.Integer:3, java.lang.String:trois java.lang.Integer:4, java.lang.String:quatre 1 java.lang.Integer:1, java.lang.String:un java.lang.Integer:1, java.lang.String:one -6 java.lang.Integer:1, java.lang.String:one 0

Concordia University Department of Computer Science and Software Engineering Angelika Langer. Java Generics FAQJava Generics FAQ Gilad Bracha. Generics in the Java Programming Language.Generics in the Java Programming Language Paul Gibson. Generics (in Java)Generics (in Java) David R. Musser, Alexander A. Stepanov. Generic Programming. In International Symposium on Symbolic and Algebraic Computation (ISSAC 1988). Lecture Notes in Computer Science 358, Springer-Verlag, 1989, pp Generic Programming Ronald Garcia, Jaakko Jarvi, Andrew Lumsdaine, Jeremy G. Siek, and Jeremiah Willcock. A Comparative Study of Language Support for Generic Programming. SIGPLAN Not. 38, 11 (October 2003), doi= / A Comparative Study of Language Support for Generic Programming Charles W. Krueger. Software reuse. ACM Comput. Surv. 24, 2 (June 1992), doi= / Software reuse Ross Tate, Alan Leung, Sorin Lerner. Taming Wildcards in Java’s Type System. Technical Report. Cornell University.Taming Wildcards in Java’s Type System Joseph A. Goguen. Parameterized Programming. IEEE Trans. Softw. Eng. 10, 5 (September 1984), doi= /TSE Parameterized Programming References Joey Paquet, SOEN Advanced Programming Practices

Concordia University Department of Computer Science and Software Engineering Mads Torgersen, Christian Plesner Hansen, Erik Ernst, Peter von der Ahé, Gilad Bracha, and Neal Gafter. Adding wildcards to the Java programming language. In Proceedings of the 2004 ACM symposium on Applied computing (SAC '04). ACM, New York, NY, USA, doi= / Adding wildcards to the Java programming language java.boot.by. SCJP Tiger Study Guide. Collections/Generics.Collections/Generics java2novice.com. Java Generics Sample Code.Java Generics Sample Code References Joey Paquet, SOEN Advanced Programming Practices