SlideShare a Scribd company logo
Generics for Dummies 
...or how to shoot an elephant 
from five feet, and miss! 
Knut Mork – 22.2.2005
"The increase in complexity is increasing, 
in part because of the natural, inevitable trend of technology 
to put together ever-more powerful solutions 
to problems we never realized we had.” 
Donald Norman
Traditional example 
List myIntList = new ArrayList(); 
myIntList.add(new Integer(0)); 
Integer x = (Integer) myIntList.iterator().next(); 
Same example using generics 
List<Integer> myIntList = new ArrayList<Integer>(); 
myIntList.add(new Integer(0)); 
Integer x = myIntList.iterator().next();
Excerpt from java.util: 
public interface List<E> { 
void add(E x); 
Iterator<E> iterator(); 
} 
public interface Iterator<E> { 
E next(); 
boolean hasNext(); 
}
• What ? 
– To abstract over types 
• Why ? 
– Safer code, eliminate run-time checks 
– Strong typing (not loose info) 
– Remove (visible) down-casting 
– Reduce awful, but necessary javadoc comments 
– Increase the indend of your code/interface 
– Others ? 
• Where ? 
– Collections, reflection (but problems with impl), others ? 
• When ? 
– Introduced in Java 1.5
No more casting ? 
Basket<Fruit> basket = new Basket<Fruit>(); 
basket.addElement(new Apple()); 
Apple apple = (Apple) basket.pickElement();
Simple, right? 
... wrong!
“Any fool can write code that a computer can understand. 
Good programmers write code that humans can understand.” 
Martin Fowler
Real example from java.util.Collections: 
public static <T extends Object & 
Comparable<? super T>> max(Collection<? extends T> coll) 
public static Object max(Collection coll) JDK 1.5 
JDK 1.4
Example - subtyping 
List<String> ls = new ArrayList<String>(); 
List<Object> lo = ls; 
lo.add(new Object()); 
String s = ls.get(0);
Example - subtyping 
List<String> ls = new ArrayList<String>(); 
List<Object> lo = ls; // compile-time error 
lo.add(new Object()); 
String s = ls.get(0);
Traditional example2 
void printCollection(Collection c) { 
Iterator i = c.iterator(); 
for(k = 0; k < c.size(); k++) { 
System.out.println(i.next()); 
} 
} 
Same example2 using generics 
void printCollection(Collection<Object> c) { 
for(Object e : c) { 
System.out.println(e); 
} 
}
Traditional example2 
void printCollection(Collection c) { 
Iterator i = c.iterator(); 
for(k = 0; k < c.size(); k++) { 
System.out.println(i.next()); 
} 
} 
Same example2 using generics 
void printCollection(Collection<?> c) { 
for(Object e : c) { 
System.out.println(e); 
} 
}
But, on the other hand... 
Collection<?> c = new ArrayList<String>(); 
c.add(new Object()); // compile-time error
It gets worse... 
”The single biggest enemy of reliability 
(and perhaps software quality in general) 
is complexity.” 
Bertrand Meyer
Bounded Wildcards 
public void eatAll (List<Fruit> fruites) { 
for (Fruit f: fruites) { 
f.eat(this); 
} 
} 
public void eatAll(List<? extends Fruit> fruites) { 
... 
}
Bounded Wildcards 
public void addBanana(List<? extends Fruit> fruites) { 
fruites.add(0, new Banana()); 
}
Bounded Wildcards 
public void addBanana(List<? extends Fruit> fruites) { 
fruites.add(0, new Banana()); // compile-time error 
}
...a lot worse... 
"Once a satisfactory product has been achieved, 
further change may be counterproductive, 
especially if the product is successful. 
You have to know when to stop.” 
Donald Norman
Example 3 
static void fromArrayToCollection(Object[] a, Collection c) { 
for (Object o : a) { 
c.add(o); 
} 
}
Example 3 
static void fromArrayToCollection(Object[] a, Collection c) { 
for (Object o : a) { 
c.add(o); 
} 
} 
Generic version: 
static void fromArrayToCollection(Object[] a, Collection<?> c) { 
for (Object o : a) { 
c.add(o); 
} 
}
Example 3 
static void fromArrayToCollection(Object[] a, Collection c) { 
for (Object o : a) { 
c.add(o); 
} 
} 
Generic version: 
static void fromArrayToCollection(Object[] a, Collection<?> c) { 
for (Object o : a) { 
c.add(o); // compile-time error 
} 
}
Example 3 
static void fromArrayToCollection(Object[] a, Collection c) { 
for (Object o : a) { 
c.add(o); 
} 
} 
Generic working version: 
static <T> void fromArrayToCollection(T[] a, Collection<T> c) { 
for (T o : a) { 
c.add(o); 
} 
}
”Under the hood” 
”When simple things need instruction, 
it is a certain sign of poor design.” 
Donald Norman
Traditional example 
List myIntList = new ArrayList(); 
myIntList.add(new Integer(0)); 
Integer x = (Integer) myIntList.iterator().next(); 
Same example using generics 
List<Integer> myIntList = new ArrayList<Integer>(); 
myIntList.add(new Integer(0)); 
Integer x = myIntList.iterator().next();
List <String> l1 = new ArrayList<String>(); 
List<Integer> l2 = new ArrayList<Integer>(); 
System.out.println(l1.getClass() == l2.getClass()); 
Output result ?
Collection cs = new ArrayList<String>(); 
if(cs instanceof Collection<String>) {...} 
Output result ?
Legacy code interoperability 
"You must not give the world what it asks for, 
but what it needs.” 
Edsger Dijkstra
Using legacy code in 1.5 
List fruitList1 = new ArrayList<Fruit>(); 
fruitList1.add(new Apple()); // warning 
List fruitList2 = new ArrayList(); 
fruitList2 = juggle(fruitList2); // warning 
List<Fruit> fruitList3 = new ArrayList<Fruit>(); 
fruitList3 = eat(fruitList3); // warning 
public List eat(List fruits) {...} 
public List<Fruit> juggle(List<Fruit> fruits) {...}
Using legacy code in 1.5 
public String loophole(Integer x) { 
List<String> ys = new ArrayList<String>(); 
List xs = ys; 
xs.add(x); // compile-time unchecked warning 
return ys.iterator().next(); 
}
Example of warnings given: 
Unsafe type operation: 
Should not assign expression of raw type List to type List<Foo>. 
References to generic type List<E> should be parameterized. 
Unsafe type operation: 
The method bar(List<Foo>) in the type SimpleExample should not 
be applied for the arguments (List). References to generic types 
should be parameterized.
...and even worse... 
"Once a satisfactory product has been achieved, 
further change may be counterproductive, 
especially if the product is successful. 
You have to know when to stop.” 
Donald Norman
• A type parameter cannot be referenced in a static context 
• Runtime type check with instanceof and casting on generic types have no meaning 
• Arrays of generic types are not permitted 
• For overloading, it is not enough to use wildcards for formal parameter types 
• Generic classes can be extended 
– The subclass provides the actual type parameters for the superclass 
• For overriding, the return type of the method in the subclass can now be identical or 
a subtype of the return type of the method in the superclass 
• A generic class cannot be a subclass of Throwable 
• Type parameters are allowed in the throws clause, but not for the parameter of the 
catch block 
• Varargs with a parameterized type are not legal
Introduction of characters with new special meaning 
<, > ? T, E, ... 
super & 
”Programs must be written for people to read, 
and only incidentally for machines to execute.” 
Abelson and Sussman
Which ones will compile ? 
a) Basket b = new Basket(); 
b) Basket b1 = new Basket<Fruit>(); 
c) Basket<Fruit> b2 = new Basket<Fruit>(); 
d) Basket<Apple> b3 = new Basket<Fruit>(); 
e) Basket<Fruit> b4 = new Basket<Apple>(); 
f) Basket<?> b5 = new Basket<Apple>(); 
g) Basket<Apple> b6 = new Basket<?>();
Thoughts and comments 
Anyone ? 
Is this a good thing or not ? 
Is it an important feature of the language ? 
What if this was included in the first version ? 
Would the design be different/easier ? 
Would users use it differently ? 
When should we use it ? If we should, that is! 
Why can’t we find other good examples, but the collection ones ?
Still interested ? 
• Intro paper: 
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf 
• Angelika’s F.A.Q. 
http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html
”There are two ways of constructing a software design: 
One way is to make it so simple 
that there are obviously no deficiencies, 
and the other way is to make it so complicated 
that there are no obvious deficiencies. 
The first method is far more difficult.” 
C. A. R. Hoare

More Related Content

What's hot

Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Stacks
StacksStacks
Stacks
Sadaf Ismail
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
Ganesh Samarthyam
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
Vadim Dubs
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
Muhammad Alhalaby
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 

What's hot (19)

Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Stacks
StacksStacks
Stacks
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
Java programs
Java programsJava programs
Java programs
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 

Viewers also liked

java Jdbc
java Jdbc java Jdbc
java Jdbc
Ankit Desai
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
CodeOps Technologies LLP
 
Java awt
Java awtJava awt
Java awt
Arati Gadgil
 
Java Swing
Java SwingJava Swing
Java Swing
Shraddha
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
Adil Mehmoood
 
java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)
Daroko blog(www.professionalbloggertricks.com)
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Awt
AwtAwt

Viewers also liked (12)

Java AWT
Java AWTJava AWT
Java AWT
 
java Jdbc
java Jdbc java Jdbc
java Jdbc
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java awt
Java awtJava awt
Java awt
 
Java Swing
Java SwingJava Swing
Java Swing
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)
 
java swing
java swingjava swing
java swing
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Awt
AwtAwt
Awt
 

Similar to Java Generics for Dummies

Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5ecomputernotes
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
ecomputernotes
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
Henri Tremblay
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
ShashikantSathe3
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
Jaanus Pöial
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
Manuela Grindei
 
Java 104
Java 104Java 104
Java 104
Manuela Grindei
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
franciscoortin
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
Tak Lee
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
sholavanalli
 

Similar to Java Generics for Dummies (20)

Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Clean Code
Clean CodeClean Code
Clean Code
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
Collections
CollectionsCollections
Collections
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
Java 104
Java 104Java 104
Java 104
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 

Recently uploaded

Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 

Recently uploaded (20)

Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 

Java Generics for Dummies

  • 1. Generics for Dummies ...or how to shoot an elephant from five feet, and miss! Knut Mork – 22.2.2005
  • 2. "The increase in complexity is increasing, in part because of the natural, inevitable trend of technology to put together ever-more powerful solutions to problems we never realized we had.” Donald Norman
  • 3. Traditional example List myIntList = new ArrayList(); myIntList.add(new Integer(0)); Integer x = (Integer) myIntList.iterator().next(); Same example using generics List<Integer> myIntList = new ArrayList<Integer>(); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();
  • 4. Excerpt from java.util: public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); }
  • 5. • What ? – To abstract over types • Why ? – Safer code, eliminate run-time checks – Strong typing (not loose info) – Remove (visible) down-casting – Reduce awful, but necessary javadoc comments – Increase the indend of your code/interface – Others ? • Where ? – Collections, reflection (but problems with impl), others ? • When ? – Introduced in Java 1.5
  • 6. No more casting ? Basket<Fruit> basket = new Basket<Fruit>(); basket.addElement(new Apple()); Apple apple = (Apple) basket.pickElement();
  • 8. “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” Martin Fowler
  • 9. Real example from java.util.Collections: public static <T extends Object & Comparable<? super T>> max(Collection<? extends T> coll) public static Object max(Collection coll) JDK 1.5 JDK 1.4
  • 10. Example - subtyping List<String> ls = new ArrayList<String>(); List<Object> lo = ls; lo.add(new Object()); String s = ls.get(0);
  • 11. Example - subtyping List<String> ls = new ArrayList<String>(); List<Object> lo = ls; // compile-time error lo.add(new Object()); String s = ls.get(0);
  • 12. Traditional example2 void printCollection(Collection c) { Iterator i = c.iterator(); for(k = 0; k < c.size(); k++) { System.out.println(i.next()); } } Same example2 using generics void printCollection(Collection<Object> c) { for(Object e : c) { System.out.println(e); } }
  • 13. Traditional example2 void printCollection(Collection c) { Iterator i = c.iterator(); for(k = 0; k < c.size(); k++) { System.out.println(i.next()); } } Same example2 using generics void printCollection(Collection<?> c) { for(Object e : c) { System.out.println(e); } }
  • 14. But, on the other hand... Collection<?> c = new ArrayList<String>(); c.add(new Object()); // compile-time error
  • 15. It gets worse... ”The single biggest enemy of reliability (and perhaps software quality in general) is complexity.” Bertrand Meyer
  • 16. Bounded Wildcards public void eatAll (List<Fruit> fruites) { for (Fruit f: fruites) { f.eat(this); } } public void eatAll(List<? extends Fruit> fruites) { ... }
  • 17. Bounded Wildcards public void addBanana(List<? extends Fruit> fruites) { fruites.add(0, new Banana()); }
  • 18. Bounded Wildcards public void addBanana(List<? extends Fruit> fruites) { fruites.add(0, new Banana()); // compile-time error }
  • 19. ...a lot worse... "Once a satisfactory product has been achieved, further change may be counterproductive, especially if the product is successful. You have to know when to stop.” Donald Norman
  • 20. Example 3 static void fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); } }
  • 21. Example 3 static void fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); } } Generic version: static void fromArrayToCollection(Object[] a, Collection<?> c) { for (Object o : a) { c.add(o); } }
  • 22. Example 3 static void fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); } } Generic version: static void fromArrayToCollection(Object[] a, Collection<?> c) { for (Object o : a) { c.add(o); // compile-time error } }
  • 23. Example 3 static void fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); } } Generic working version: static <T> void fromArrayToCollection(T[] a, Collection<T> c) { for (T o : a) { c.add(o); } }
  • 24. ”Under the hood” ”When simple things need instruction, it is a certain sign of poor design.” Donald Norman
  • 25. Traditional example List myIntList = new ArrayList(); myIntList.add(new Integer(0)); Integer x = (Integer) myIntList.iterator().next(); Same example using generics List<Integer> myIntList = new ArrayList<Integer>(); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();
  • 26. List <String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getClass()); Output result ?
  • 27. Collection cs = new ArrayList<String>(); if(cs instanceof Collection<String>) {...} Output result ?
  • 28. Legacy code interoperability "You must not give the world what it asks for, but what it needs.” Edsger Dijkstra
  • 29. Using legacy code in 1.5 List fruitList1 = new ArrayList<Fruit>(); fruitList1.add(new Apple()); // warning List fruitList2 = new ArrayList(); fruitList2 = juggle(fruitList2); // warning List<Fruit> fruitList3 = new ArrayList<Fruit>(); fruitList3 = eat(fruitList3); // warning public List eat(List fruits) {...} public List<Fruit> juggle(List<Fruit> fruits) {...}
  • 30. Using legacy code in 1.5 public String loophole(Integer x) { List<String> ys = new ArrayList<String>(); List xs = ys; xs.add(x); // compile-time unchecked warning return ys.iterator().next(); }
  • 31. Example of warnings given: Unsafe type operation: Should not assign expression of raw type List to type List<Foo>. References to generic type List<E> should be parameterized. Unsafe type operation: The method bar(List<Foo>) in the type SimpleExample should not be applied for the arguments (List). References to generic types should be parameterized.
  • 32. ...and even worse... "Once a satisfactory product has been achieved, further change may be counterproductive, especially if the product is successful. You have to know when to stop.” Donald Norman
  • 33. • A type parameter cannot be referenced in a static context • Runtime type check with instanceof and casting on generic types have no meaning • Arrays of generic types are not permitted • For overloading, it is not enough to use wildcards for formal parameter types • Generic classes can be extended – The subclass provides the actual type parameters for the superclass • For overriding, the return type of the method in the subclass can now be identical or a subtype of the return type of the method in the superclass • A generic class cannot be a subclass of Throwable • Type parameters are allowed in the throws clause, but not for the parameter of the catch block • Varargs with a parameterized type are not legal
  • 34. Introduction of characters with new special meaning <, > ? T, E, ... super & ”Programs must be written for people to read, and only incidentally for machines to execute.” Abelson and Sussman
  • 35. Which ones will compile ? a) Basket b = new Basket(); b) Basket b1 = new Basket<Fruit>(); c) Basket<Fruit> b2 = new Basket<Fruit>(); d) Basket<Apple> b3 = new Basket<Fruit>(); e) Basket<Fruit> b4 = new Basket<Apple>(); f) Basket<?> b5 = new Basket<Apple>(); g) Basket<Apple> b6 = new Basket<?>();
  • 36. Thoughts and comments Anyone ? Is this a good thing or not ? Is it an important feature of the language ? What if this was included in the first version ? Would the design be different/easier ? Would users use it differently ? When should we use it ? If we should, that is! Why can’t we find other good examples, but the collection ones ?
  • 37. Still interested ? • Intro paper: http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf • Angelika’s F.A.Q. http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html
  • 38. ”There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” C. A. R. Hoare

Editor's Notes

  1. Fra det første eksemplet, hvordan signatur klassene/interfacene som ble brukt blir definert
  2. Java var ikke de første til å introdusere denne språk-featuren, vis kanskje med eksempel med templates i c++
  3. Skriv ned resten av deklarasjonene på tavla... Eller ta dem høyt! Et annet tilfelle på casting er ved uthenting av objekter fra JNDI-tre
  4. Vis FAQ-siden til Angelika (http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html) Vis javadoc på collection api’et (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html)
  5. Hva er navnet på metoden ? Hva tar metoden som parameter ??? Hvorfor er den blitt så kompleks ? Pga bakoverkomp – skal ikke være mer begrensende enn tidligere versjoner
  6. FØRSTE PROBLEM! En og en linje...
  7. Ta på tavla – G&amp;lt;Foo&amp;gt; !subtype G&amp;lt;Bar&amp;gt;, selv om Foo subtype Bar (Bruk Basket/fruit/apple eksemplet)
  8. Hva er feil med det nederste eksemplet ? Collection of unknown: Collection&amp;lt;?&amp;gt;
  9. Hva er feil med det nederste eksemplet ? Collection of unknown: Collection&amp;lt;?&amp;gt; Wildcard type Vi kan fortsatt lese elementer og gi dem typen Object. Men...
  10. Men, å assigne et Object til resultatet av get() er lov!
  11. Før denne slide, gi eksempel-koden først Hva betyr den første metoden ? Jo, f.eks. Kan vi ikke kalle på denne med List&amp;lt;Apple&amp;gt; (Apple er subtype av Fruit)
  12. Hvorfor gir denne feil ? Typen til den andre parameteren er en ukjent subtype av Fruit. Denne behøver ikke nødvendigvis være en supertype til Banana Tegn bokser klasse-hierarki
  13. Hvorfor gir denne feil ? Typen til den andre parameteren er en ukjent subtype av Fruit. Denne behøver ikke nødvendigvis være en supertype til Banana Tegn bokser klasse-hierarki
  14. Spør publikum hvordan denne kan løses, og begynn å skriv metoden på tavla ...men bør overskriften egentlig være her ? Det kan være tull å introdusere alle ”ordene” i generics-ordboka... Kanskje lettere å bare vise de ulike tingene ???
  15. Spør publikum hvordan denne kan løses
  16. Spør publikum hvordan denne kan løses
  17. Kan man nå f.eks. ha en array av Stringer og en Collection av Objecter ? JA! T definisjonen kan f.eks. også ha ”extends” og andre ting i seg!
  18. Hvorfor er det nødvendig å kunne (eller bare å si) noe om dette her ? Svar: Dårlig design/implementasjonen påvirker interfacet!
  19. Vis hvordan koden ser ut etter å ha kjørt JAD. Erasior
  20. True
  21. Hvorfor gir denne feil ?
  22. Unchecked warnings will occur
  23. Vil gi feil i runtime!
  24. Hentet fra foredrag på javazone... Var så morsom (fordi man blir bare helt oppgitt) at jeg måtte ta den med... ...og på neste slide til vedkommende, så står det med store bokstaver: ”GENERIC FUN HAS JUST BEGUN” Why not ? Unntak er kjedelig (les: gjør ting vanskeligere) Årsaken til noen her er erasure valget!
  25. Kanskje bedre å tegne på tavla Som er nesten definisjonen på økt kompleksitet/økt vanskelighet. Og dette er bare for generics... Andre så som ”:” er også lagt til i 1.5
  26. Teste litt kunnskaper helt til slutt