G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.

Slides:



Advertisements
Similar presentations
Sml2java a source to source translator Justin Koser, Haakon Larsen, Jeffrey Vaughan PLI 2003 DP-COOL.
Advertisements

New features in JDK 1.5 Can these new and complex features simplify Java development?
Java Review Interface, Casting, Generics, Iterator.
Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Generic programming in Java
Java Generics.
Generic Programming David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
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.
Generic Programming Amit Shabtay. March 3rd, 2004 Object Oriented Design Course 2 The Problem Assume we have a nice Stack implementation. Our stack receives.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our 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.
Generics. Type parameters The definition of “ArrayApplier” in applier.java and applier2.java allows any function from int to int. But suppose you want.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
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.
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.
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.
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.
Generics CompSci 230 S Software Construction.
Types in programming languages1 What are types, and why do we need them?
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
Peyman Dodangeh Sharif University of Technology Spring 2014.
CMSC 330: Organization of Programming Languages Java Generics.
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.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
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.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
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.
Generic Programming David Rabinowitz.
Java Generics.
Generic(Parameterized ) Types
Generic Programming David Rabinowitz.
Generics.
Java Generics.
Generics.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

G ENERICS The feature of Generics in Java allows Applications to create classes and objects that can operate on any defined types. It prevents un-necessary casting being done in the Application code and prevents any wrong data-type being used.

C ONSIDER A CODE SNIPPET List list = new ArrayList(); list.add(new String(“hello”)); String s = (String)list.iterator().next();

P ROBLEM WITH A BOVE CODE Wrong Input: list.add(new Integer(0)); Casting can also lead to run time error. Unecessary Casting: String s = (String)list.iterator().next();

C ODE USING GENERICS List list = new ArrayList (); list.add(“hello”); String str = list.iterator().next(); //No need of String st = list.get(0); //Casting list.add(new Integer(0)); // Compilation Error

D EFINING S IMPLE GENERICS public interface List { void add(E x); Iterator iterator(); } public interface Iterator { E next(); boolean hasNext(); } In the invocation -Formal type parameters are replaced by Actual type parameters (Integer, String, etc).

T HIS IS HOW IT LOOKS LIKE !! public interface List { void add(String x); Iterator iterator(); }

U NDERSTANDING G ENERICS Is this code legal! List ls = new ArrayList (); List lo = ls; //lo used as an alias to ls Question: Is a List of String a List of Object?? lo.add(new Object()); String s = ls.get(0); // attempts to assign an object to a string!

G ENERAL P OINTS ABOUT G ENERICS.. Previous code gives compile time error. In general, if Foo is a subtype(subclass or subinterface) of Bar, and G is some generics type declaration, it is not the case that G is a subtype of G.

W RITING G ENERIC CLASSES ObjectHolder.java public class ObjectHolder { private O anyObject; public O getObject() { return anyObject; } public void setObject(O anyObject) { this.anyObject = anyObject; } public String toString() { return anyObject.toString(); }

C ODE USING PREVIOUS GENERIC CLASS ObjectHolderClient.java import java.net.URL; public class ObjectHolderClient { public static void main(String[] args) throws Exception { ObjectHolder stringHolder = new ObjectHolder (); stringHolder.setObject(new String("String")); System.out.println(stringHolder.toString()); ObjectHolder urlHolder = new ObjectHolder (); urlHolder.setObject(new URL(" System.out.println(urlHolder.toString()); }

G ENERIC METHODS A Generic class containing a type parameter affects the entire class, but a generic method containing one or more type parameters affects that particular method only. Non-generic class can contain a mixture of generic and non- generic methods. public class GenericMethods { static void printType(T anyType) { System.out.println(anyType.getClass().getName()); } public static void main(String[] args) { GenericMethods.printType(String.class); GenericMethods.printType(new String("")); }

W ILDCARDS Consider: List strObjects = new ArrayList (); List anotherStrObjects = strObjects; // legal List objects = strObjects; // Compile Error Object someObject = new String(""); //legal SOLUTION! List objects = strObjects;

The character '?' is a wild-card character and it stands for any Java type. List anyObjects = null; List integers = new ArrayList (); anyObjects = integers; List doubles = new ArrayList (); anyObjects = doubles;

E XCEPTIONS ! Since the type parameter for the reference anyObjects is '?', no objects can be added to the collection, not even java.lang.Object anyObjects.add(new Integer(1)); // Won’t compile anyObjects.add(new Double(1.0)); // Wont compile Null is an Exception to that. anyObjects.add(null); // This will compile

B OUNDING THE PARAMETRIC TYPES public class AnimalActions Only extends keyword is used for both class as well the interface and not the implements keyword. If we want the parametric type to confirm by more than one classes or interfaces, then every types should be separated by the symbol &.

T WO CHOICES FOR COMPILER Code specialization- The compiler generates a new representation for every instantiation of a generic type or method. For instance, the compiler would generate code for a list of integers and additional, different code for a list of strings, a list of dates, a list of buffers, and so on. Code sharing. The compiler generates code for only one representation of a generic type or method and maps all the instantiations of the generic type or method to the unique representation, performing type checks and type conversions where needed.

T YPE ERASURE A process that maps a parameterized type (or method) to its unique byte code representation by eliding type parameters and arguments. The compiler generates only one byte code representation of a generic type or method and maps all the instantiations of the generic type or method to the unique representation. This mapping is performed by type erasure.

H OW ACTUALLY COMPILATION TAKES PLACE List list = new ArrayList (); list.add("Hi"); String x = list.get(0); Is converted to List list = new ArrayList(); list.add("Hi"); String x = (String) list.get(0);

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. To maintain binary compatibility with Java libraries and applications that were created before generics. For instance, Box is translated to type Box, which is called the raw type

This means that you can't find out what type of Object a generic class is using at runtime. public class MyClass { public static void myMethod(Object item) { if ( item instanceof E ) { …………….. //Compiler error } E item2 = new E(); //Compiler error E[] iArray = new E[10]; //Compiler error }

R EFERENCES java.sun.com/j2se/1.5/pdf/ generics - tutorial.pdf www. java beat.net/articles/33- generics-in- java html AQSections/TechnicalDetails.html#FAQ100

T HANKS !