More on Java Generics Multiple Generic Types Bounded Generic Types

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.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Generic programming in Java
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Java Generics.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
CPSC150 Interfaces Chapter CPSC150 Inheritance Review No different than any other class. Has no access to or information about subclasses class.
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
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.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
©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.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
CSC 243 – Java Programming, Spring 2013 March 12, 2013 Week 7, Generics.
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.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Introduction to Generics
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CMSC 330: Organization of Programming Languages Java Generics.
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.
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.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Generics.
ADT’s, Collections/Generics and Iterators
John Hurley Cal State LA
Chapter 20 Generic Classes and Methods
Generics and Subtyping
A tree set Our SearchTree class is essentially a set.
Fundamental of Java Programming
Generics, Lambdas, Reflections
Generics.
Java Generics.
Chapter 9 Inheritance and Polymorphism
Chapter 19 Generics Dr. Clincy - Lecture.
Generics (Parametric Polymorphism)
Java Programming Language
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
A tree set Our SearchTree class is essentially a set.
Generics.
Generic programming in Java
Chapter 19 Generics.
Generics, Lambdas, Reflections
CS2013 Lecture 3 John Hurley Cal State LA.
CSC 220 – Processing Spring, 2017
Java Programming Language
Review: libraries and packages
Winter 2019 CMPE212 5/3/2019 CMPE212 – Reminders
Chapter 19 Generics.
CSE 143 Lecture 21 Advanced List Implementation
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
Chapter 19 Generics.
Presentation transcript:

More on Java Generics Multiple Generic Types Bounded Generic Types Wild Cards Raw Types versus Parameterized Types Meta-data / Annotations

Multiple Generic Types Multiple generic types in a class Example: TreeMap<K, V> The default TreeMap constructor assumes K implements Comparable, but K is not specified K extends Comparable The overloaded TreeMap constructor with a Comparator parameter does not assume it

Bounded Generic Types Bounded Generic Types <T extends Class> is a bounded generic type T must be Class or some subclass of Class <T extends Interface> is also a bounded type T must be an implementing class of Interface Note syntax is using extends for either: implements (interface) or extends (inheritance)

Bounded Generic Types Defining a class with a bounded type public class Generic<T extends Comparable> { … } Using a class with a bounded generic type Generic<Comparable> g1 = new Generic<Comparable>(); Generic<String> g2 = new Generic<String>(); Generic<NotComparable> g3 = new Generic<NotComparable>(); // error

Bounded Generic Types Lower Bound Generic Types <T super Class> is a lower-bound generic type T must be Class or some superclass of Class Defining a class with a lower bound type public class Generic<T super Stack> { … } Using a class with a lower bound type Generic<Vector> g4 = new Generic<Vector>(); Generic<Stack> g5 = new Generic<Stack>();

Bounded Generic Types But even though there is a superclass and subclass relationship between the generic types involved, it is not a valid widening conversion for classes parameterized with related generic types

Bounded Generic Types Remember a class with a bounded generic type class Generic<T extends Comparable> Generic<Comparable> g1 = … Generic<String> g2 = … However, assignment won’t work g1 = g2; // is a compiler error // Generic<String> is not // a valid subtype of // Generic<Comparable>

Wildcards However, we can get around some of the preceding restrictions by using wildcards Wildcard Generic Types <?> is an extended wildcard same as <? extends Object> <? extends T> is a bounded wildcard ? must be T or some subclass of T <? super T> is a lower-bound wildcard ? must be T or some superclass of T

Wildcards Use as a variable type Integer is a subtype of Number List<Integer> is not a subtype of List<Number> However, with a wildcard we can get Integer elements out of a List<? extends Number> List<Integer> ints = Arrays.asList(1,2); List<? extends Number> nums = ints; for(Number n : nums) System.out.println(n);

Wildcards Use as a type for a method parameter: boolean addAll(Collections<? extends T> c) Another collection containing a subtype of T can be added to a collection of type T ArrayList<Comparable> c = new . . . ; ArrayList<String> s = new . . . ; c.addAll(s);

Wildcards We can’t use a wildcard in the class header where a dummy generic type will need to be used in code public class ClassName<?> public class ClassName<? extends Number> How could we write lines of code that refer to the generic type for this ? class? ? myQuestionMark = ... // compiler is  public ? myMethod() // compiler is 

Evolution, not Revolution An important goal in the generic design was to ensure that Java 4.2 legacy code would work with the Java 5.0 generic library Java recognizes the un-parameterized type of each parameterized class/interface in the library, e.g. Iterable and Iterable<T> The parameterized types are subtypes of the corresponding un-parameterized “raw” type used in the legacy code

Evolution, not Revolution Legacy code used “raw” un-parameterized types for its reference variables pertaining to the now parameterized types in the Java 5.0 class library ArrayList myList = new ArrayList(); A value of a parameterized type can be passed where a raw type is expected – a normal widening conversion A value of a raw type can also be passed where a parameterized type is expected, but the compiler produces an “unchecked” warning

Evolution, not Revolution You also get warnings on passing of object references where type <T> is expected Use compiler switch –source 1.4 or add annotations to the legacy code to suppress these warnings: @SuppressWarnings(“unchecked”) But if you are editing the legacy source, why not just make it generic instead?

Meta-data/Annotations In JDK 5.0, a dedicated annotation facility was added, probably due to success of C#'s attributes One of the first practical uses of annotations is a as a way to suppress compiler warnings @SupressWarnings(“type of warning”) This allows the developer to signal a “respecting” compiler that it should forgo a particular warning It is up to the compiler to make sense of whatever you put inside the string, the only value mandated in Java Language Specification is "unchecked"

Meta-data/Annotations Compilers as well as IDE's implement their own set of warning types, e.g. the Eclipse IDE defines more than NetBeans does See a compiler’s support with javac -X Sun JDK1.6.0_03 supports types : cast, deprecation, divzero, empty, unchecked, fallthrough, path, serial, finally, overrides

Meta-data/Annotations The following code would get two warnings public void uncheckedTest() {  List nonGenericList = new ArrayList();  nonGenericList.add("Some string");  List<String> genericStringList = (List<String>)nonGenericList; } warning: [unchecked] unchecked call to add(E) as member of the raw type java.util.List nonGenericList.add("Some string"); warning: [unchecked] unchecked cast found : java.util.List required: java.util.List List genericStringList = (List)nonGenericList;

Meta-data/Annotations We can use “unchecked” to avoid warnings on unchecked casts when using generics It can be applied in front of a type, a field, a method, a parameter, a constructor as well as a local variable @SuppressWarnings(“unchecked”) public void uncheckedTest() { …