Creating Generic Classes. Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering.

Slides:



Advertisements
Similar presentations
INF 212 ANALYSIS OF PROG. LANGS Type Systems Instructors: Crista Lopes Copyright © Instructors.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Generics and The ArrayList Class
Generic programming in Java
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
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.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
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.
„Generics and collections”. Generics and collections Generics From JDK They are similar to C++ templates They allow to eliminate runtime exceptions.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
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.
Java Programming II 1 Generic Types and Inner Classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMING PRACTICES Java generics.
Java Generics.
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.
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.
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.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMING PRACTICES Java generics.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Saint Petersburg, 2011 Java Lecture Generics. Quiz ArrayList lst = new ArrayList(); Collection c = lst; lst.add("one"); lst.add(“two"); lst.add(“three");
Types in programming languages1 What are types, and why do we need them?
Introduction to Generics
Generic Instructor : Sarah Alodan. Problem?! Java code used to look like this: public class Courses { public static void main(String[] args) { ArrayList.
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.
Generics in C# 1. Generics List vs. non-generic ArrayList Generic List Namespace System.Collections.Generic List list = new List (); List.add(”Anders”);
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
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 –
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
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.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Sixth Lecture ArrayList Abstract Class and Interface
Advanced Program Design with C++
Polymorphism.
Introduction to Java Programming
Generic programming in Java
Review: libraries and packages
Generic Programming.
Chapter 19 Generics.
Subtype Substitution Principle
Presentation transcript:

Creating Generic Classes

Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering casts when working with collections. ArrayList list = new ArrayList(); list.add(“foo”); String e = (String) list.get(0);// cast is annoying Integer e = (Integer)list.get(0); //runtime error!

Generics Many Java classes (including all Collections) were retrofitted to use generic types as: ArrayList slist= new ArrayList (); slist.add(“hello”); //compiler can check! String s = slist.get(0); //no cast required This is read as “An ArrayList of String”. Obviously, any object can be used, String just an example.

Autoboxing The native datatype wrapper classes (Integer, Double, Float, etc.) have a special property when used with generics. LinkedList list = new LinkedList (); list.add(3); //new Integer(3) not necessary! int i = list.get(0); //returns a native int This feature saves wrapping and unwrapping native types. It is separate from but goes hand in hand with generics.

Some gotchas This is all pretty simple – using classes built on generics not much harder than using classes based on Object. There are a few gotchas though even at list level. The most common are: – instanceof will not work with parameterized types – arrays of parameterized types are illegal E.g. ArrayList [] list = new ArrayList [3]; //NO!

View from the other side Sometimes you might need to create your own generic classes. This is considered a bit more of an advanced topic, but everyone should be familiar with the basics. We go into much more detail in Advanced Java.

** * Generic version of the Box class. the type of value being boxed */ public class Box { private T t; // T stands for "Type" public void add(T t) { this.t = t; } public T get() { return t; } Using Box signals that users can create Boxes of any type. it is also possible to have generic methods within classes that themselves are not Generic.

Using the Box class class BoxDemo3 { public static void main(String[] args) { Box integerBox = new Box (); //as of 1.7 ok to use Box i = new Box(); integerBox.add(new Integer(10)); Integer someInteger = integerBox.get(); // no cast! int someIntegerAsNativeType = integerBox.get(); //autoboxing System.out.println(someInteger); }

public class Box { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public void inspect(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.add(new Integer(10)); integerBox.inspect("some text"); } Signals that the method takes a generic type parameter (U by convention). u is of type U Generic type parameters for methods

public class Box { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public void inspect(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.add(new Integer(10)); integerBox.inspect("some text"); // error: this is still String! } Bounded type parameters. Read as “anything that extends Number”. Float ok but String not, e.g.

A couple of more gotchas You cannot instantiate type variables! T obj = new T(); //NO This can be worked around with reflection but it is really ugly. Consider other alternatives. You cannot throw or catch instances of a generic class