The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.
( ** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ** )
This Edureka tutorial on “Java ArrayList” (Java blog series: https://goo.gl/osrGrS) will give you a brief insight about ArrayList in Java and its various constructors and methods along with an example. Through this tutorial, you will learn the following topics:
Collections Framework
Hierarchy of ArrayList
What is ArrayList
Internal Working of ArrayList
Constructors of ArrayList
Constructors Example
ArrayList Methods
Methods Example and Demo
Advantages of ArrayList over Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/CRbgFann
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.
( ** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ** )
This Edureka tutorial on “Java ArrayList” (Java blog series: https://goo.gl/osrGrS) will give you a brief insight about ArrayList in Java and its various constructors and methods along with an example. Through this tutorial, you will learn the following topics:
Collections Framework
Hierarchy of ArrayList
What is ArrayList
Internal Working of ArrayList
Constructors of ArrayList
Constructors Example
ArrayList Methods
Methods Example and Demo
Advantages of ArrayList over Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/CRbgFann
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
A class is a template / blue print is used to create an object. In JavaScript class is a special kind of function. In JavaScript there are two ways to create class one is the class declaration and the second one is class expressions.
Garbage collection has largely removed the need to think about memory management when you write Java code, but there is still a benefit to understanding and minimizing the memory usage of your applications, particularly with the growing number of deployments of Java on embedded devices. This session gives you insight into the memory used as you write Java code and provides you with guidance on steps you can take to minimize your memory usage and write more-memory-efficient code. It shows you how to
• Understand the memory usage of Java code
• Minimize the creation of new Java objects
• Use the right Java collections in your application
• Identify inefficiencies in your code and remove them
Video available from Parleys.com:
https://www.parleys.com/talk/how-write-memory-efficient-java-code
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
Some parts of our applications don't need to be asynchronous or interact with the outside world: it's enough that they are stateful, possibly with the ability to handle failure, context, and logging. Although you can use ZIO 2 or monad transformers for this task, both come with drawbacks. In this presentation, Jorge Vásquez will introduce you to ZPure, a data type from ZIO Prelude, which lets you scale back on the power of ZIO 2, but with the same high-performance, type-inference, and ergonomics you expect from ZIO 2 libraries.
This presentation introduces some concepts about the Java Collection framework. These slides introduce the following concepts:
- Collections and iterators
- Linked list and array list
- Hash set and tree set
- Maps
- The collection framework
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
Collections and its types in C# (with examples)Aijaz Ali Abro
Learn step by step c# collections with easy examples. Learn generic, non-generic and specialized collections along with easy and great examples. Learn about arraylist, queue class,stack class and more. Difference between generic and non-generic collections. Difference between arraylist and simple array.
This is an overview of C++ (based on 1999 / 2003 standard) and its use in Object Oriented Programming. The presentation assumes that the audience knows C programming.
Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.
Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety”
The Java collections framework supports generics to specify the type of objects stored in a collection instance.
A class is a template / blue print is used to create an object. In JavaScript class is a special kind of function. In JavaScript there are two ways to create class one is the class declaration and the second one is class expressions.
Garbage collection has largely removed the need to think about memory management when you write Java code, but there is still a benefit to understanding and minimizing the memory usage of your applications, particularly with the growing number of deployments of Java on embedded devices. This session gives you insight into the memory used as you write Java code and provides you with guidance on steps you can take to minimize your memory usage and write more-memory-efficient code. It shows you how to
• Understand the memory usage of Java code
• Minimize the creation of new Java objects
• Use the right Java collections in your application
• Identify inefficiencies in your code and remove them
Video available from Parleys.com:
https://www.parleys.com/talk/how-write-memory-efficient-java-code
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
Some parts of our applications don't need to be asynchronous or interact with the outside world: it's enough that they are stateful, possibly with the ability to handle failure, context, and logging. Although you can use ZIO 2 or monad transformers for this task, both come with drawbacks. In this presentation, Jorge Vásquez will introduce you to ZPure, a data type from ZIO Prelude, which lets you scale back on the power of ZIO 2, but with the same high-performance, type-inference, and ergonomics you expect from ZIO 2 libraries.
This presentation introduces some concepts about the Java Collection framework. These slides introduce the following concepts:
- Collections and iterators
- Linked list and array list
- Hash set and tree set
- Maps
- The collection framework
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
Collections and its types in C# (with examples)Aijaz Ali Abro
Learn step by step c# collections with easy examples. Learn generic, non-generic and specialized collections along with easy and great examples. Learn about arraylist, queue class,stack class and more. Difference between generic and non-generic collections. Difference between arraylist and simple array.
This is an overview of C++ (based on 1999 / 2003 standard) and its use in Object Oriented Programming. The presentation assumes that the audience knows C programming.
Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.
Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety”
The Java collections framework supports generics to specify the type of objects stored in a collection instance.
Software development effort reduction with Co-oplbergmans
This talks explains the motivations for the Co-op technology: what are the challenges it addresses, in particular focusing on reducing accidental complexity, where it comes from, and a general vision on how to resolve it. Then we continue to show practical application of Co-op, including experience figures from large-scale application of a previous generation of this technology. Show a little bit about its realization, and conclude with an evaluation of the technology.
we recap the basic and advanced notions regarding different types of Object types used when working in UiPath environment. We are going to go through the basics (e.g.: concatenation, conversion between different types of data) and deep dive into more advanced topics like linqs or selectors, recap how to work with datatables, from initialization to filtering and touch upon the subject of invoking code inside an UiPath project.
Certification preparation - Net classses and functions.pptxRohit Radhakrishnan
we recap the basic and advanced notions regarding different types of Object types used when working in UiPath environment. We are going to go through the basics (e.g.: concatenation, conversion between different types of data) and deep dive into more advanced topics like linqs or selectors, recap how to work with datatables, from initialization to filtering and touch upon the subject of invoking code inside an UiPath project.
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMURaffi Khatchadourian
Java 8 default methods, which allow interfaces to contain (instance) method implementations, are useful for the skeletal implementation software design pattern. However, it is not easy to transform existing software to exploit default methods. In this talk, I discuss an efficient, fully-automated, type constraint-based refactoring approach that assists developers in taking advantage of enhanced interfaces for their legacy Java software.
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. This talk will detail several new key features of Java 8 that can help make programs easier to read, write, and maintain. Java 8 comes with many features, especially related to collection libraries. We will cover such new features as Lambda Expressions, the Stream API, enhanced interfaces, and more.
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. This talk will detail several new key features of Java 8 that can help make programs easier to read, write, and maintain. Java 8 comes with many features, especially related to collection libraries. We will cover such new features as Lambda Expressions, the Stream API, enhanced interfaces, and more.
Some Pitfalls with Python and Their Possible Solutions v1.0Yann-Gaël Guéhéneuc
Python is a very popular programming language that comes with many pitfalls. This presentation describes some of these pitfalls, especially when they could trick unsuspecting object-oriented developers. It proposes solutions to these pitfalls, in particular regarding inheritance, which is easily broken because of the implementation choice of Python for explicit delegation, its method resolution order, and its use of the C3 algorithm. It discusses some advantages of using Python, especially regarding meta-classes.
Advice for writing a NSERC Discovery grant application v0.5Yann-Gaël Guéhéneuc
NSERC Discovery grant applications are judged according to four criteria: (1) Excellence of the researcher, (2) Merit of the proposal, (3) Contribution to the training of HQP, and (4) Cost of research. Each criterion has six possible merit indicators: Exceptional, Outstanding, Very strong, Strong, Moderate, and Insufficient. This presentation describes the process from a candidate's point of view and a reviewer's point of view. It discusses funding decisions, including bins and ER vs. ECR. It gives some advice, including graduating PhD students, having a story, and limiting the number of main objectives.
Ptidej Architecture, Design, and Implementation in Action v2.1Yann-Gaël Guéhéneuc
A set of process, architecture, design, and implementation patterns from a real, large program, the Ptidej Tool Suite. This set shows concrete problems and their solutions in Java. It includes: Be A Profiler, Tests as Documentation, Multi-layered Architecture, Proxy Console, Proxy Disk, Hidden Language, Internal Observer, Run-time Deprecation, String Parsimony, Object Identity, Object Address, Final Construction, StringBuffer as Positioning Element.
Examples of (bad) consequences of a lack of software quality and some solutions. This presentation presents some examples of (bad) consequences of a lack of software quality, in particular how poor software quality led to the direct deaths of 89 people. It then provides some background on software quality, especially the concept of Quality Without a Name. It then discusses many principles, their usefulness, and their positive consequences on software quality. Some of these principles are well-known in object-oriented programming while many others are taken from the book 97 Programmers. They include: abstraction, encapsulation, inheritance, types, polymorphism, SOLID, GRASP, YAGNI, KISS, DRY, Do Not Reinvent the Wheel, Law of Demeter, Beware of Assumptions, Deletable Code, coding with reason, and functional programming. They pertain to dependencies, domains, and tools.
(In details: Beautify is Simplicity, The Boy Scout Rule, You Gotta Care About the Code, The Longevity of Interim Solutions, Beware the Share, Encapsulate Behaviour not Just State, Single Responsibility Principle, WET Dilutes Performance Bottlenecks, Convenience Is Not an -ility, Code in the Language of the Domain, Comment Only What the Code Cannot Say, Distinguish Business Exception from Technical, Prefer Domain-specific Types to Primitive Types, Automate Your Coding Standards, Code Layout Matters, Before You Refactor, Improve Code by Removing It, Put the Mouse Down and Step Away from the Keyboard)
Some Pitfalls with Python and Their Possible Solutions v0.9Yann-Gaël Guéhéneuc
Python is a very popular programming language that comes with many pitfalls. This presentation describes some of these pitfalls, especially when they could trick unsuspecting object-oriented developers. It proposes solutions to these pitfalls, in particular regarding inheritance, which is easily broken because of the implementation choice of Python for explicit delegation, its method resolution order, and its use of the C3 algorithm. It discusses some advantages of using Python, especially regarding meta-classes.
An Explanation of the Unicode, the Text Encoding Standard, Its Usages and Imp...Yann-Gaël Guéhéneuc
Unicode is currently the world standard for encoding text. It supports all of the world's major writing systems. With its version 15.1 of 2023/09/12, it defines 149,813 characters and 161 scripts. This presentation starts with the, seemingly, simple example of the polar bear emoji. It then defines the key terms of any such standard. It then asks how a software system can render orthographic characters into glyphs, i.e., to render characters into (combined) glyphs. It introduces the concept of abstract characters and describes a brief history of encoding standards, from ASCII to Unicode. It shows how, by adding one level of indirection, the Unicode standard answers this question. It then presents code examples to display text written in Unicode: HarfBuzz (for shaping) and FreeType (for rendering).
An Explanation of the Halting Problem and Its ConsequencesYann-Gaël Guéhéneuc
The halting problem is an important, famous, and consequential problem in computer science. It is about writing a program that decides if another problem will stop. There is no general solution to this problem, which shows that such a problem is undecidable, with important consequences: for example, it is not possible to write tests that would exhaustively test entirely an arbitrary program. This presentation was written in collaboration with <a href="https://www.iro.umontreal.ca/~hahn/">Gena Hahn</a>.
A presentation summarising FPGAs, their history, their benefits, and showing how to program them. It provides some historical background on the development of computers, from the Difference Engine to the Intel 4004 to the AMD Ryzen Threadripper PRO 3995WX. It shows how the number of transistors increased dramatically but also how this increase led to more complexity and more bugs. It then introduces Field-programmable gate arrays (FPGA) as an alternative. It then presents how to program such FPGA using data-flow graphs. It discusses some tools (Yosys, NextPnR, and IceStorm) and illustrates them with a typical "Hello World" (i.e., blinking an LED) using Cygwin on Windows 10.
A set of brief presentations of some of the women and men who made the history of computer science and software engineering.
- 1936: Alan Turing
- 1948: Claude Elwood Shannon
- 1950: Grace Murray Hopper
- 1960: John McCarthy
- 1966: Frances E. Allen
- 1967: Ole-Johan Dahl
- 1967: Kristen Nygaard
- 1969: Charles A. R. Hoare
- 1970: Edgar F. Codd
- 1972: Dave Parnas
- 1974: Manny Lehman
- 1975: Frederick Brooks
- 1986: Edward Yourdon
- 1987: Barbara Liskov
- 1994: Erich Gamma
- 1997: Grady Booch
- 2001: Butler Lampson
A tutorial on the history, use, and caveats of Java generics. Using the simple example of an interface for sort algorithms, the tutorial presents the history of generics and describes the problems being solved by generics. It also provides definitions, and examples in Java and C++, and discusses Duck Typing. It then describes two scenarios: (1) Scenario 1: you want to enforce type safety for containers and remove the need for typecasts when using these containers and (2) Scenario 2: you want to build generic algorithms that work on several types of (possibly unrelated) things. It also summarises caveats with generics, in particular type erasure.
A tutorial on reflection, with a particular emphasis on Java, with a comparison with C++, Python, and Smalltalk. It describes different scenarios in which reflection is useful, a brief history of reflection and MOPs, a comparison with C++, Python, and Smalltalk, and some particulars about Java. The source code of the examples in Java (Eclipse project), Smalltalk (Squeak image v3.10.6), Python (Eclipse project), and C++ (Eclipse projects and Visual Studio solution) are available. (C++ Eclipse projects require Mirror.) Big thanks to Matúš Chochlík and Marcus Denker for their kind and precious help with C++ and Smalltalk.
The tutorial focuses on four common problems:
- Avoid using instanceof when code must bypass the compiler and virtual machine’s choice of the method to call.
- Create external, user-defined pieces of code loaded, used, and unloaded at run-time.
- Translate data structures or object states into a format that can be stored (file, network...).
- Monitor the execution of a program to understand its behaviour, and measure its space and time complexity.
It shows working examples of Java, Smalltalk, Python, and C++ code solving the four common problems through four scenarios:
- Scenario 1: invoke an arbitrary method on an object (see the problems with instanceof and plugins).
- Scenario 2: access the complete (including private) state of an object (see the problem with serialisation).
- Scenario 3: count the number of instances of a class created at runtime (see the problem with debugging/profiling).
- Scenario 4: patch the method of a class to change its behaviour (see the problem with patching).
It also discusses the different kinds of interconnections among objects that are available in common programming languages (linking, forking, subclassing, inter-process communication, and dynamic loading/invoking), a bit of theory about reflection, and specifically the class-loading mechanism of Java.
REST APIs are nowadays the de-facto standard for Web applications. However, as more systems and services adopt the REST architectural style, many problems arise regularly. To avoid these repetitive problems, developers should follow good practices and avoid bad practices. Thus, research on good and bad practices and how to design a simple but effective REST API are essential. Yet, to the best of our knowledge, there are only a few concrete solutions to recurring REST API practices, like “API Versioning”. There are works on defining or detecting some practices, but not on solutions to the practices. We present the most up-to-date list of REST API practices and formalize them in the form of REST API (anti)patterns. We validate our design (anti)patterns with a survey and interviews of 55 developers.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
How world-class product teams are winning in the AI era by CEO and Founder, P...
On Parameterised Types and Java Generics
1. Yann-Gaël Guéhéneuc
Département de génie informatique et de génie logiciel
This work is licensed under a Creative
Commons Attribution-NonCommercial-
ShareAlike 3.0 Unported License
Java
Generics
yann-gael.gueheneuc@polytmtl.ca
Version 1.1
2014/05/12
2. 2/171
Any questions/comments are welcome at
yann-gael.gueheneuc@polymtl.ca
Source code available at
http://www.ptidej.net/tutorials/javagenerics
3. 3/171
2013/03/22 – v1.0 – First version of the slides
2013/04/19 – v1.0.1 – Fixed some typos
2014/05/12 – v1.1 – Added example of mixing objects
Cited PECS explanations
Added more generated bytecodes
Fixed some typos
4. 4/171
Problem
Sorting lists does not and should not depend
on the type of the elements stored in the list
import java.util.List;
public interface ISort {
public List sort(final List aList);
}
5. 5/171
Problem
Sorting lists does not and should not depend
on the type of the elements stored in the list
Problem: elements may not be comparable
Solution: generic typing with Comparable
6. 6/171
Problem
Sorting lists assumes (and is sure) that the
elements stored in the list are comparable
import java.util.List;
public interface ISort<E extends Comparable<E>> {
public List<E> sort(final List<E> aList);
}
7. 7/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
8. 8/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
9. 9/171
History
1983: Reynolds formalises the parametricity
theorem, called abstraction theorem
– Functions with similar types have similar
properties
John C. Reynolds
*1935
John C. Reynolds ; “Types, abstraction, and parametric polymorphism” ; Information
Processing ; pp. 513–523, North Holland, 1983.
10. 10/171
History
Parametric polymorphism
– Expressiveness
– Type-safety
• First implementation in ML in 1989 (1976?)
append: [a] [a] [a]
Robin Milner, Robert Harper, David MacQueen, and Mads Tofte ; “The Definition Of Standard
ML” ; The MIT Press, 1997.
11. 11/171
History
Parametric polymorphism
– Expressiveness
– Type-safety
• First implementation in ML in 1989 (1976?)
append: [a] [a] [a]
Robin Milner, Robert Harper, David MacQueen, and Mads Tofte ; “The Definition Of Standard
ML” ; The MIT Press, 1997.
Explicit parametric
polymorphism
12. 12/171
History
1988: David Musser and Alexander
Stepanov define the concept of generic
programming
– Abstractions from examples of algorithms and
data structure
– Concept of “concept”
David R. Musser and Alexander A. Stepanov ; “Generic Programming” ; International
symposium on Symbolic and Algebraic Computation, pp. 13-25, ACM Press, 1988.
Alexander Stepanov
*1950
David Musser
*c.1945
13. 13/171
History
“Generic programming is about abstracting
and classifying algorithms and data
structures. […] Its goal is the incremental
construction of systematic catalogs of useful,
efficient and abstract algorithms and data
structures.”
—Alexander Stepanov
14. 14/171
History
Generic programming
– Theory of iterators
– Independent of implementation
• C++ Standard Template Library (STL)
const ::std::vector<Foo>::iterator theEnd = theContainer.end();
for ( ::std::vector<Foo>::iterator i = theContainer.begin();
i != theEnd;
++i ) {
Foo &cur_element = *i;
// Do something…
}
15. 15/171
History
1994: the GoF defines parameterized types
“Also known as generics (Ada, Eiffel) and
templates (C++)”
“A type that leaves some constituent types
unspecified. The unspecified types are supplied
as parameters at the point of use.”
16. 16/171
History 19771980: Ada
– 2005: generic container library
1985: Eiffel
Bertrand Meyer ; Object-Oriented Software
Construction ; Prentice Hall, 1988.
1991: C++
http://www.stroustrup.com/hopl2.pdf
– 1994: STL (under Stepanov’s guidance)
2004: Java
– Type erasure
2005: C#
– Reified generics
17. 17/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
18. 18/171
Problem
“Implement generic algorithms that work on
a collection of different types”
—The Java Tutorials, Oracle
http://docs.oracle.com/javase/tutorial/java/generics/why.html
19. 19/171
Problem
Sorting lists does not and should not depend
on the type of the elements stored in the list
import java.util.List;
public interface ISort {
public List sort(final List aList);
}
20. 20/171
Problem
Sorting lists does not and should not depend
on the type of the elements stored in the list
Problem: elements may not be comparable
Solution: generic typing with Comparable
21. 21/171
Problem
Sorting lists does not and should not depend
on the type of the elements stored in the list
import java.util.List;
public interface ISort<E extends Comparable<E>> {
public List<E> sort(final List<E> aList);
}
22. 22/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
23. 23/171
Special Case
package net.ptidej.generics.java;
public class Example1 {
public static void main(final String[] args) {
final Object[] arrayOfObjects = new Object[10];
final String[] arrayOfStrings = new String[20];
System.out.println(arrayOfObjects.length);
System.out.println(arrayOfStrings.length);
System.out.println(arrayOfObjects[0]);
System.out.println(arrayOfStrings[2]);
System.out.println(arrayOfObjects.clone());
System.out.println(arrayOfStrings.toString());
}
}
24. 24/171
Special Case
Array are (often) predefined generic types
final Object[] arrayOfObjects = new Object[10];
final String[] arrayOfStrings = new String[20];
25. 25/171
Special Case
Array are (often) predefined generic types
final Object[] arrayOfObjects = new Object[10];
final String[] arrayOfStrings = new String[20];
Any type can go here
27. 27/171
Special Case
Every new array instantiates a new concrete
type (or reuse an existing concrete type)
New concrete type
(pseudo-type in Java)
28. 28/171
Special Case
Syntax and semantics built in the compiler
System.out.println(arrayOfObjects.length);
System.out.println(arrayOfStrings.length);
System.out.println(arrayOfObjects[0]);
System.out.println(arrayOfStrings[2]);
System.out.println(arrayOfObjects.clone());
System.out.println(arrayOfStrings.toString());
29. 29/171
Special Case
Syntax and semantics built in the compiler
Pseudo-field
System.out.println(arrayOfObjects.length);
System.out.println(arrayOfStrings.length);
System.out.println(arrayOfObjects[0]);
System.out.println(arrayOfStrings[2]);
System.out.println(arrayOfObjects.clone());
System.out.println(arrayOfStrings.toString());
30. 30/171
Special Case
Syntax and semantics built in the compiler
Pseudo-field
System.out.println(arrayOfObjects.length);
System.out.println(arrayOfStrings.length);
System.out.println(arrayOfObjects[0]);
System.out.println(arrayOfStrings[2]);
System.out.println(arrayOfObjects.clone());
System.out.println(arrayOfStrings.toString());
Access, a[b]
31. 31/171
Special Case
Syntax and semantics built in the compiler
Pseudo-field
System.out.println(arrayOfObjects.length);
System.out.println(arrayOfStrings.length);
System.out.println(arrayOfObjects[0]);
System.out.println(arrayOfStrings[2]);
System.out.println(arrayOfObjects.clone());
System.out.println(arrayOfStrings.toString());
Access, a[b]
In the Java programming language
arrays are objects (§4.3.1), are
dynamically created, and may be
assigned to variables of type Object
(§4.3.2). All methods of class Object
may be invoked on an array.
—JLS
32. 32/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
34. 34/171
General Definitions
Ad-hoc polymorphism
– Method overloading
– Not a feature of the type system
– Dispatch mechanism
• Typically, dispatch depends on the concrete type of
the receiver of a method
Christopher Strachey ; “Fundamental Concepts in Programming Languages” ; Higher-Order and
Symbolic Computation, volume 13, issue 1-2, pp. 11-49, Springer, 2000.
35. 35/171
General Definitions
Ad-hoc polymorphism
– A name may have more than one meaning
• It may refer to more than one algorithm
– The choice of the algorithm is context-
dependent but know at compile-time
(Early binding when compared to the following
subtype polymorphism)
36. 36/171
General Definitions
Subtype polymorphism
– Liskov substitution principle
• Let q(x) be a property provable about objects x
of type T. Then q(y) should be true for objects y
of type S where S is a subtype of T
(Late binding when compared to the previous
ad hoc polymorphism)
Barbara Liskov
*1939
37. 37/171
General Definitions
Subtype polymorphism
package net.ptidej.generics.java;
import java.awt.Frame;
import java.lang.Long;
public class Example3 {
public static void main(final String[] args) {
Object o;
o = new Long(1);
System.out.println(o.toString());
o = new Frame();
System.out.println(o.toString());
}
}
38. 38/171
General Definitions
Subtype polymorphism
package net.ptidej.generics.java;
import java.awt.Frame;
import java.lang.Long;
public class Example3 {
public static void main(final String[] args) {
Object o;
o = new Long(1);
System.out.println(o.toString());
o = new Frame();
System.out.println(o.toString());
}
}
Declared type vs.
concrete types
39. 39/171
General Definitions
Parametric polymorphism
public class NonGenericBox {
private Object object;
public void set(final Object object) {
this.object = object;
}
public Object get() {
return this.object;
}
}
public void useOfNonGenericBox() {
final NonGenericBox aNonGenericBox = new NonGenericBox();
aNonGenericBox.set(new String());
final String myString = (String) aNonGenericBox.get();
System.out.println(myString);
}
40. 40/171
General Definitions
Parametric polymorphism
public class NonGenericBox {
private Object object;
public void set(final Object object) {
this.object = object;
}
public Object get() {
return this.object;
}
}
public void useOfNonGenericBox() {
final NonGenericBox aNonGenericBox = new NonGenericBox();
aNonGenericBox.set(new String());
final String myString = (String) aNonGenericBox.get();
System.out.println(myString);
}
Must cast to ask
compiler to allow
the assignment
41. 41/171
General Definitions
Parametric polymorphism
public class NonGenericBox {
private Object object;
public void set(final Object object) {
this.object = object;
}
public Object get() {
return this.object;
}
}
public void useOfNonGenericBox() {
final NonGenericBox aNonGenericBox = new NonGenericBox();
aNonGenericBox.set(new String());
final Integer myInteger = (Integer) aNonGenericBox.get();
System.out.println(myInteger);
}
42. 42/171
General Definitions
Parametric polymorphism
public class NonGenericBox {
private Object object;
public void set(final Object object) {
this.object = object;
}
public Object get() {
return this.object;
}
}
public void useOfNonGenericBox() {
final NonGenericBox aNonGenericBox = new NonGenericBox();
aNonGenericBox.set(new String());
final Integer myInteger = (Integer) aNonGenericBox.get();
System.out.println(myInteger);
}
Legal!
47. 47/171
General Definitions
Parametric polymorphism
Type parameter
Generic type
declaration
We use Java vocabulary in the following
Parameterised
methods
Type variable
48. 48/171
General Definitions
Parametric polymorphism
Type parameter
Generic type
declaration
We use Java vocabulary in the following
Type argument
Parameterised
methods
Type variable
49. 49/171
General Definitions
Parametric polymorphism
public class GenericBox<T> {
private T t;
public void set(final T t) {
this.t = t;
}
public T get() {
return this.t;
}
}
public void useOfGenericBox() {
final GenericBox<String> aGenericBox = new GenericBox<String>();
aGenericBox.set(new String());
final String myString = aGenericBox.get();
System.out.println(myString);
}
50. 50/171
General Definitions
Parametric polymorphism
public class GenericBox<T> {
private T t;
public void set(final T t) {
this.t = t;
}
public T get() {
return this.t;
}
}
public void useOfGenericBox() {
final GenericBox<String> aGenericBox = new GenericBox<String>();
aGenericBox.set(new String());
final Integer myInteger = (Integer) aNonGenericBox.get();
System.out.println(myInteger);
}
51. 51/171
General Definitions
Parametric polymorphism
public class GenericBox<T> {
private T t;
public void set(final T t) {
this.t = t;
}
public T get() {
return this.t;
}
}
public void useOfGenericBox() {
final GenericBox<String> aGenericBox = new GenericBox<String>();
aGenericBox.set(new String());
final Integer myInteger = (Integer) aNonGenericBox.get();
System.out.println(myInteger);
}
Illegal!
52. 52/171
General Definitions
Parametric polymorphism
package net.ptidej.generics.java;
public class Example4 {
public static void main(final String[] args) {
System.out.println(Util.<String>compare("a", "b"));
System.out.println(Util.<String>compare(new String(""), new Long(1)));
System.out.println(Util.compare(new String(""), new Long(1)));
}
}
public class Util {
public static <T> boolean compare(T t1, T t2) {
return t1.equals(t2);
}
}
53. 53/171
General Definitions
Parametric polymorphism
package net.ptidej.generics.java;
public class Example4 {
public static void main(final String[] args) {
System.out.println(Util.<String>compare("a", "b"));
System.out.println(Util.<String>compare(new String(""), new Long(1)));
System.out.println(Util.compare(new String(""), new Long(1)));
}
}
public class Util {
public static <T> boolean compare(T t1, T t2) {
return t1.equals(t2);
}
}
Generic method
54. 54/171
General Definitions
Parametric polymorphism
package net.ptidej.generics.java;
public class Example4 {
public static void main(final String[] args) {
System.out.println(Util.<String>compare("a", "b"));
System.out.println(Util.<String>compare(new String(""), new Long(1)));
System.out.println(Util.compare(new String(""), new Long(1)));
}
}
public class Util {
public static <T> boolean compare(T t1, T t2) {
return t1.equals(t2);
}
}
Generic method
Explicit calls
55. 55/171
General Definitions
Parametric polymorphism
package net.ptidej.generics.java;
public class Example4 {
public static void main(final String[] args) {
System.out.println(Util.<String>compare("a", "b"));
System.out.println(Util.<String>compare(new String(""), new Long(1)));
System.out.println(Util.compare(new String(""), new Long(1)));
}
}
public class Util {
public static <T> boolean compare(T t1, T t2) {
return t1.equals(t2);
}
}
Generic method
Explicit calls
Implicit call
56. 56/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
58. 58/171
Generics Definitions
Java generics are one implementation of
parametric polymorphism
– Type erasure
Type parameters can be constrained
– Lower bounds
– Upper bounds
to obtain bounded type parameters
59. 59/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
60. 60/171
Generics Definitions
Parametric polymorphism
– Predicative
• ML
– Impredicative
• System F
• C++, Java 1.5
– Bounded
• C++ in one way, Java 1.5 in another
Martín Abadi, Luca Cardelli, Pierre-Louis Curien ; “Formal Parametric Polymorphism” ; SRC
research report, issue 109, Digital, Systems Research Center, 1993.
61. 61/171
Generics Definitions
Predicative parametric polymorphism
– A type T containing a type variable may not be
used in such a way that is instantiated to a
polymorphic type
62. 62/171
Generics Definitions
Predicative parametric polymorphism
– A type T containing a type variable may not be
used in such a way that is instantiated to a
polymorphic type
final GenericBox<String> aGenericBox = new GenericBox<String>();
aGenericBox.set(new String());
final GenericBox<List<String>> aGenericBox = new GenericBox<List<String>>();
aGenericBox.set(new String());
63. 63/171
Generics Definitions
Predicative parametric polymorphism
– A type T containing a type variable may not be
used in such a way that is instantiated to a
polymorphic type
final GenericBox<String> aGenericBox = new GenericBox<String>();
aGenericBox.set(new String());
final GenericBox<List<String>> aGenericBox = new GenericBox<List<String>>();
aGenericBox.set(new String());
65. 65/171
Generics Definitions
Impredicative parametric polymorphism
– Example 1
– Example 2
final GenericBox<List<String>> aGenericBox = new GenericBox<List<String>>();
aGenericBox.set(new String());
66. 66/171
Generics Definitions
Impredicative parametric polymorphism
– Example 1
– Example 2
import java.util.List;
public interface ISort<E extends Comparable<E>> {
public List<E> sort(final List<E> aList);
}
final GenericBox<List<String>> aGenericBox = new GenericBox<List<String>>();
aGenericBox.set(new String());
67. 67/171
Generics Definitions
Bounded parametric polymorphism
The type E of the list elements must implement
the interface Comparable
import java.util.List;
public interface ISort<E extends Comparable<E>> {
public List<E> sort(final List<E> aList);
}
68. 68/171
Generics Definitions
Bounded parametric polymorphism
“Bounded genericity is less about limiting the
types accepted by [a] generic class […] and
more about giving the generic class a more
complete information on its generic type T […] to
validate the call to its methods at compile time.”
—paercebal
http://stackoverflow.com/questions/6803100/achieving-bounded-genericity-in-c/6803124
69. 69/171
GenericsDefinitions
public class Example5 {
public static void main(final String[] args) {
final Sort<A> sort = new Sort<A>();
final List<A> listOfAs = new ArrayList<A>();
sort.sort(listOfAs);
System.out.println();
}
}
class Sort<E extends Comparable<E>> {
public List<E> sort(final List<E> aList) {
return // TO DO
}
}
class A implements Comparable<A> {
public int compareTo(final A o) {
return // TO DO
}
}
class B implements Comparable<B> {
public int compareTo(final B o) {
return // TO DO
}
}
70. 70/171
GenericsDefinitions
public class Example5 {
public static void main(final String[] args) {
final Sort<A> sort = new Sort<A>();
final List<A> listOfAs = new ArrayList<A>();
sort.sort(listOfAs);
System.out.println();
}
}
class Sort<E extends Comparable<E>> {
public List<E> sort(final List<E> aList) {
return // TO DO
}
}
class A implements Comparable<A> {
public int compareTo(final A o) {
return // TO DO
}
}
class B implements Comparable<B> {
public int compareTo(final B o) {
return // TO DO
}
}
Must be comparable (with itself)
71. 71/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
73. 73/171
Generics Definitions
Other bounded parametric polymorphisms
“This feature is provided as-is and where-used
by the compiler: in a way similar to duck typing,
but resolved at compile-time. [Compilation
succeeds] only if the generic type class
[declares] the [expected method].”
—paercebal
http://stackoverflow.com/questions/6803100/achieving-bounded-genericity-in-c/6803124
74. 74/171
GenericsDefinitions class X {
public:
virtual void kewl_method() { /* etc. */ }
};
class Y: public X {
public:
virtual void kewl_method() { /* etc. */ }
};
class Z {
public:
virtual void kewl_method() { /* etc. */ }
};
class K {
public:
virtual void wazaa() { /* etc. */ }
};
template<typename T>
class A {
public:
void foo() {
T t;
t.kewl_method();
}
};
75. 75/171
GenericsDefinitions class X {
public:
virtual void kewl_method() { /* etc. */ }
};
class Y: public X {
public:
virtual void kewl_method() { /* etc. */ }
};
class Z {
public:
virtual void kewl_method() { /* etc. */ }
};
class K {
public:
virtual void wazaa() { /* etc. */ }
};
template<typename T>
class A {
public:
void foo() {
T t;
t.kewl_method();
}
};
No common type
76. 76/171
GenericsDefinitions class X {
public:
virtual void kewl_method() { /* etc. */ }
};
class Y: public X {
public:
virtual void kewl_method() { /* etc. */ }
};
class Z {
public:
virtual void kewl_method() { /* etc. */ }
};
class K {
public:
virtual void wazaa() { /* etc. */ }
};
template<typename T>
class A {
public:
void foo() {
T t;
t.kewl_method();
}
};
Common API
77. 77/171
GenericsDefinitions
int main()
{
// A's constraint is : implements kewl_method
A<X> x ; x.foo() ;
// OK: x implements kewl_method
A<Y> y ; y.foo() ;
// OK: y derives from X
A<Z> z ; z.foo() ;
// OK: z implements kewl_method
A<K> k ; k.foo() ;
// NOT OK : K won't compile: /main.cpp error:
// ‘class K’ has no member named ‘kewl_method’
return 0;
}
78. 78/171
GenericsDefinitions
“Static” duct typing
int main()
{
// A's constraint is : implements kewl_method
A<X> x ; x.foo() ;
// OK: x implements kewl_method
A<Y> y ; y.foo() ;
// OK: y derives from X
A<Z> z ; z.foo() ;
// OK: z implements kewl_method
A<K> k ; k.foo() ;
// NOT OK : K won't compile: /main.cpp error:
// ‘class K’ has no member named ‘kewl_method’
return 0;
}
79. 79/171
Generics Definitions
Duck typing
– Dynamically-typed languages: Smalltalk
– Statically-typed language: C++
“When I see a bird that walks like a duck and
swims like a duck and quacks like a duck, I call
that bird a duck.”
—Alex Martelli or James W. Riley
85. 85/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
86. 86/171
When to Use Generics
Scenario 1: you want to enforce type safety
for containers and remove the need for
typecasts when using these containers
public final class Example1 {
public static void main(final String[] args) {
final List untypedList = new ArrayList();
untypedList.add(new String());
final Integer i = (Integer) untypedList.get(0);
final List<String> typedList = new ArrayList<String>();
typedList.add(new String());
final Integer i = (Integer) typedList.get(0);
}
}
Does not compile
87. 87/171
When to Use Generics
Scenario 2: you want to build generic
algorithms that work on several types of
(possible unrelated) things
import java.util.List;
public interface ISort<E extends Comparable<E>> {
public List<E> sort(final List<E> aList);
}
88. 88/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
89. 89/171
How to Use Generics
Lots of resources
Lots of discussions
First step http://docs.oracle.com/javase/
tutorial/java/generics/index.html
Then, http://stackoverflow.com/search?
q=%22java+generics%22
– 1,323 results as of 2013/04/14
90. 90/171
How to Use Generics
Typed containers, before
import java.util.ArrayList;
import java.util.List;
public final class Example1Before {
public static void main(final String[] args) {
final List untypedList = new ArrayList();
untypedList.add(new String());
final Integer i = (Integer) untypedList.get(0);
}
}
91. 91/171
How to Use Generics
Typed containers, what happens?
import java.util.ArrayList;
import java.util.List;
public final class Example1Before {
public static void main(final String[] args) {
final List untypedList = new ArrayList();
untypedList.add(new String());
final Integer i = (Integer) untypedList.get(0);
}
}
92. 92/171
How to Use Generics
Typed containers, what happens?
import java.util.ArrayList;
import java.util.List;
public final class Example1Before {
public static void main(final String[] args) {
final List untypedList = new ArrayList();
untypedList.add(new String());
final Integer i = (Integer) untypedList.get(0);
}
}
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer
at net.ptidej.generics.java.Example1Before.main(Example1Before.java:29)
93. 93/171
How to Use Generics
Typed containers, another look
import java.util.ArrayList;
import java.util.List;
public final class Example1Before {
public static void main(final String[] args) {
final List untypedList = new ArrayList();
untypedList.add(new String());
final Integer i = (Integer) untypedList.get(0);
}
}
94. 94/171
How to Use Generics
Typed containers, another look
import java.util.ArrayList;
import java.util.List;
public final class Example1Before {
public static void main(final String[] args) {
final List untypedList = new ArrayList();
untypedList.add(new String());
final Integer i = (Integer) untypedList.get(0);
}
}
List and ArrayList
are raw types, compiler
cannot typecheck
95. 95/171
How to Use Generics
Typed containers, solution
import java.util.ArrayList;
import java.util.List;
public final class Example1Before {
public static void main(final String[] args) {
final List<String> typedList = new ArrayList<String>();
typedList.add(new String());
final Integer i = (Integer) typedList.get(0);
}
}
96. 96/171
How to Use Generics
Typed containers, solution
import java.util.ArrayList;
import java.util.List;
public final class Example1Before {
public static void main(final String[] args) {
final List<String> typedList = new ArrayList<String>();
typedList.add(new String());
final Integer i = (Integer) typedList.get(0);
}
}
Does not compile because String
and Interger are not compatible
97. 97/171
How to Use Generics
Family of algorithms, before
public interface Enumeration {
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
Object nextElement();
}
98. 98/171
How to Use Generics
Family of algorithms, what happens?
public interface Enumeration {
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
Object nextElement();
}
99. 99/171
How to Use Generics
Family of algorithms, what happens?
public interface Enumeration {
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
Object nextElement();
}
Forces clients
to use Object
100. 100/171
How to Use Generics
Family of algorithms, another look
public interface Enumeration {
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
Object nextElement();
}
101. 101/171
How to Use Generics
Family of algorithms, another look
public interface Enumeration {
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
Object nextElement();
}
Clients must know the
type of the next element
102. 102/171
How to Use Generics
Family of algorithms, solution
public interface Enumeration<E> {
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
E nextElement();
}
103. 103/171
How to Use Generics
Family of algorithms, solution
public interface Enumeration<E> {
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
E nextElement();
}
104. 104/171
How to Use Generics
Family of algorithms, solution
public interface Enumeration<E> {
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
E nextElement();
}
Clients can specify the
type of the next element
105. 105/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
106. 106/171
Caveats with Generics
ints and Integers, before
public interface List extends Collection {
...
boolean add(Object o);
boolean remove(Object o);
Object remove(int index);
...
}
107. 107/171
Caveats with Generics
ints and Integers, now
public interface List<E> extends Collection<E> {
...
boolean add(E e);
boolean remove(Object o);
E remove(int index);
...
}
108. 108/171
Caveats with Generics
ints and Integers, now
public interface List<E> extends Collection<E> {
...
boolean add(E e);
boolean remove(Object o);
E remove(int index);
...
}
109. 109/171
Caveats with Generics
ints and Integers, what happens?
import java.util.ArrayList;
import java.util.List;
public class Autoboxing {
public static void main(String[] args) {
final List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(new Integer(2));
list.remove(1);
list.remove(new Integer(1));
System.out.println(list.size());
}
}
110. 110/171
Caveats with Generics
ints and Integers, what happens?
import java.util.ArrayList;
import java.util.List;
public class Autoboxing {
public static void main(String[] args) {
final List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(new Integer(2));
list.remove(1);
list.remove(new Integer(1));
System.out.println(list.size());
}
}
Autoboxing from
int to Integer
111. 111/171
Caveats with Generics
ints and Integers, what happens?
import java.util.ArrayList;
import java.util.List;
public class Autoboxing {
public static void main(String[] args) {
final List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(new Integer(2));
list.remove(1);
list.remove(new Integer(1));
System.out.println(list.size());
}
}
Autoboxing from
int to Integer
Exact parameter
matching takes
over autoboxing
112. 112/171
Caveats with Generics
ints and Integers, what happens?
import java.util.ArrayList;
import java.util.List;
public class Autoboxing {
public static void main(String[] args) {
final List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(new Integer(2));
list.remove(1);
list.remove(new Integer(1));
System.out.println(list.size());
}
}
Autoboxing from
int to Integer
Exact parameter
matching takes
over autoboxing
0
113. 113/171
Caveats with Generics
Use of clone(), before
http://stackoverflow.com/questions/3941850/
java-how-to-use-clone-and-what-about-the-cast-check
import java.util.ArrayList;
public class CloningBefore {
public static void main(final String[] args) {
final ArrayList list1 = new ArrayList();
list1.add(new Integer(1));
list1.add(new Integer(2));
final ArrayList list2 = (ArrayList) list1.clone();
System.out.println(list2);
}
}
114. 114/171
Caveats with Generics
Use of clone(), before
http://stackoverflow.com/questions/3941850/
java-how-to-use-clone-and-what-about-the-cast-check
import java.util.ArrayList;
public class CloningBefore {
public static void main(final String[] args) {
final ArrayList list1 = new ArrayList();
list1.add(new Integer(1));
list1.add(new Integer(2));
final ArrayList list2 = (ArrayList) list1.clone();
System.out.println(list2);
}
}
No complains
for the compiler
115. 115/171
Caveats with Generics
Use of clone(), now
import java.util.ArrayList;
public class CloningNow {
public static void main(final String[] args) {
final ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(new Integer(2));
final ArrayList<Integer> list2 = (ArrayList<Integer>) list1.clone();
System.out.println(list2);
}
}
116. 116/171
Caveats with Generics
Use of clone(), now
import java.util.ArrayList;
public class CloningNow {
public static void main(final String[] args) {
final ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(new Integer(2));
final ArrayList<Integer> list2 = (ArrayList<Integer>) list1.clone();
System.out.println(list2);
}
}
117. 117/171
Caveats with Generics
Use of clone(), now
import java.util.ArrayList;
public class CloningNow {
public static void main(final String[] args) {
final ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(new Integer(2));
final ArrayList<Integer> list2 = (ArrayList<Integer>) list1.clone();
System.out.println(list2);
}
}
Type safety: Unchecked cast from
Object to ArrayList<Integer>
118. 118/171
Caveats with Generics
Use of clone(), what happens?
– Compiler is now “stricter”
– Compiler warns of a type-unsafe operation
119. 119/171
Caveats with Generics
Use of clone(), solution
– Use copy-constructor
to obtain type-safety and remove any warning
import java.util.ArrayList;
public class CloningSolution {
public static void main(final String[] args) {
final ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(new Integer(2));
final ArrayList<Integer> list2 = new ArrayList<Integer>(list1);
System.out.println(list2);
}
}
120. 120/171
Caveats with Generics
Use of clone(), solution
– Use copy-constructor
to obtain type-safety and remove any warning
import java.util.ArrayList;
public class CloningSolution {
public static void main(final String[] args) {
final ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(new Integer(2));
final ArrayList<Integer> list2 = new ArrayList<Integer>(list1);
System.out.println(list2);
}
}
121. 121/171
Caveats with Generics
Use of clone(), solution
– Suppress warning
public class CloningSolutionWarning {
public static void main(final String[] args) {
final ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(new Integer(2));
@SuppressWarnings("unchecked")
final ArrayList<Integer> list2 = (ArrayList<Integer>) list1.clone();
System.out.println(list2);
}
}
122. 122/171
Caveats with Generics
Use of clone(), solution
– Suppress warning
… not really a solution!
public class CloningSolutionWarning {
public static void main(final String[] args) {
final ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(new Integer(2));
@SuppressWarnings("unchecked")
final ArrayList<Integer> list2 = (ArrayList<Integer>) list1.clone();
System.out.println(list2);
}
}
123. 123/171
Caveats with Generics
Instantiating a type variable, problem
public class InstantiatingTypeParameterProblem<T> {
public static void main(final String[] args) {
...
}
public T getInstanceOfT (){
// Neither lines work:
return new T();
return T.newInstance();
}
...
}
124. 124/171
Caveats with Generics
Instantiating a type variable, problem
public class InstantiatingTypeParameterProblem<T> {
public static void main(final String[] args) {
...
}
public T getInstanceOfT (){
// Neither lines work:
return new T();
return T.newInstance();
}
...
}
Cannot instantiate
the type T
125. 125/171
Caveats with Generics
Instantiating a type variable, problem
public class InstantiatingTypeParameterProblem<T> {
public static void main(final String[] args) {
...
}
public T getInstanceOfT (){
// Neither lines work:
return new T();
return T.newInstance();
}
...
}
Cannot instantiate
the type T
The method newInstance()
is undefined for the type T
126. 126/171
Caveats with Generics
Instantiating a type variable, what happens?
The type parameter T is erased at compile-time,
the JVM cannot use it at run-time
public class InstantiatingTypeParameterProblem<T> {
public static void main(final String[] args) {
...
}
public T getInstanceOfT (){
// Neither lines work:
return new T();
return T.newInstance();
}
...
}
127. 127/171
Caveats with Generics
Instantiating a type variable, solution #1
– Pass the class of T as parameter
public class InstantiatingTypeParameterSolution1<T> {
public static void main(final String[] args) {
...
}
public T getInstanceOfT(final Class<T> classOfT) {
return classOfT.newInstance();
}
...
}
128. 128/171
Caveats with Generics
Instantiating a type variable, solution #2
– Pass a factory of T as parameter
interface Factory<T> {
T getInstance();
}
class Something {
public static class FactoryOfSomething implements Factory<Something> {
public Something getInstance() {
return new Something();
}
}
}
public class InstantiatingTypeParameterSolution2<T> {
public static void main(final String[] args) {
...
}
public T getInstanceOfT(final Factory<T> factory) {
return factory.getInstance();
}
...
}
129. 129/171
Caveats with Generics
Instantiating a type variable, solution #3
– Prevent type erasure by specialising an
interesting class
public class InstantiatingTypeParameterSolution3 extends GenericClass<String> {
public static void main(final String[] args) {
final InstantiatingTypeParameterSolution3 i =
new InstantiatingTypeParameterSolution3();
i.foo();
}
public void foo() {
final Object s = this.getInstanceOfT();
System.out.println(s.getClass());
}
}
130. 130/171
Caveats with Generics
Instantiating a type variable, solution #3
– Prevent type erasure by specialising an
interesting class
public class InstantiatingTypeParameterSolution3 extends GenericClass<String> {
public static void main(final String[] args) {
final InstantiatingTypeParameterSolution3 i =
new InstantiatingTypeParameterSolution3();
i.foo();
}
public void foo() {
final Object s = this.getInstanceOfT();
System.out.println(s.getClass());
}
}
Type argument
and subclassing
131. 131/171
Caveats with Generics
Instantiating a type variable, solution #3
– Prevent type erasure by specialising an
interesting class
import java.lang.reflect.ParameterizedType;
abstract class GenericClass<T> {
public T getInstanceOfT() {
final ParameterizedType pt =
(ParameterizedType) this.getClass().getGenericSuperclass();
final String parameterClassName =
pt.getActualTypeArguments()[0].toString().split("s")[1];
T parameter = (T) Class.forName(parameterClassName).newInstance();
return parameter;
}
}
132. 132/171
Caveats with Generics
Instantiating a type variable, solution #3
– Prevent type erasure by specialising an
interesting class
import java.lang.reflect.ParameterizedType;
abstract class GenericClass<T> {
public T getInstanceOfT() {
final ParameterizedType pt =
(ParameterizedType) this.getClass().getGenericSuperclass();
final String parameterClassName =
pt.getActualTypeArguments()[0].toString().split("s")[1];
T parameter = (T) Class.forName(parameterClassName).newInstance();
return parameter;
}
}
The superclass is generic,
the subclass specialises it
133. 133/171
Caveats with Generics
Implicit generic methods
– As with explicit generic methods, use Object in
the generated bytecodes
public final class Example4 {
public static void main(final String[] args) {
System.out.println(Util4.<String> compare("a", "b"));
// The following line, as expected, produces a type mismatch error
// System.out.println(Util.<String> compare(new String(""), new Long(1)));
System.out.println(Util4.compare(new String(""), new Long(1)));
}
}
final class Util4 {
public static <T> boolean compare(final T t1, final T t2) {
return t1.equals(t2);
}
}
134. 134/171
Caveats with Generics
Implicit generic methods
– As with explicit generic methods, use Object in
the generated bytecodes
to ensure backward-compatibility with
non-generic Java code
// Method descriptor #15 ([Ljava/lang/String;)V
// Stack: 7, Locals: 1
public static void main(java.lang.String[] args);
…
14 invokevirtual net.ptidej.generics.java.Util44.compare(java.lang.Object, java.lang.Object) : boolean [29]
…
47 invokevirtual net.ptidej.generics.java.Util44.compare(java.lang.Object, java.lang.Object) : boolean [29]
…
135. 135/171
Caveats with Generics
Multiple bounds
“A type variable with multiple bounds is a
subtype of all the types listed in the bound.
If one of the bounds is a class, it must be
specified first.”
—The Java Tutorials, Oracle
136. 136/171
Caveats with Generics
Multiple bounds
class Example8A {
}
interface Example8B {
}
interface Example8C {
}
class Example8D<T extends Example8A & Example8B & Example8C> {
}
class Example8Test1 extends Example8A implements Example8B, Example8C {
}
class Example8Test2 extends Example8A {
}
public class Example8 {
public static void main(final String[] args) {
final Example8D<Example8Test1> d1 = new Example8D<Example8Test1>();
final Example8D<Example8Test2> d2 = new Example8D<Example8Test2>();
}
}
137. 137/171
Caveats with Generics
Multiple bounds
class Example8A {
}
interface Example8B {
}
interface Example8C {
}
class Example8D<T extends Example8A & Example8B & Example8C> {
}
class Example8Test1 extends Example8A implements Example8B, Example8C {
}
class Example8Test2 extends Example8A {
}
public class Example8 {
public static void main(final String[] args) {
final Example8D<Example8Test1> d1 = new Example8D<Example8Test1>();
final Example8D<Example8Test2> d2 = new Example8D<Example8Test2>();
}
}
Bound mismatch: The type Test2 is
not a valid substitute for the bounded
parameter <T extends …>
138. 138/171
Caveats with Generics
Upper- and lower-bounded wildcards
– Type parameters can be constrained to be
• Any subtype of a type, extends
• Any supertype of a type, super
– Useful with collections of items
import java.util.List;
public interface ISort<E extends Comparable<E>> {
public List<E> sort(final List<E> aList);
}
139. 139/171
Caveats with Generics
PECS
– Collections that produce extends
– Collections that consume super
Always from the point of view of the collection
http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs
140. 140/171
Caveats with Generics
PECS
– Collections that produce extends
• They produce elements of some types
• These types must be “topped” to tell the client that it
can safely expect to receive Somthing
• Any item from the collection is a Somthing (in the
sense of Liskov’s substitution)
Collection<? extends Something>
141. 141/171
Caveats with Generics
PECS
– Collections that consume super
• They consume elements of some types
• These types must be “bottomed” to tell the client that
it can safely put Something
• Any item in the collection is “at most” Something (in
the sense of Liskov’s substitution)
Collection<? super Something>
142. 142/171
Caveats with Generics
PECS
Another way to remember the producer /
consumer distinction is to think of a method
signature. If you have a method
useList(List), you are consuming the List
and so need covariance / extends. If your
method is List buildList(), then you are
producing the List and will need
contravariance / super
—Adapted from Raman
http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs
143. 143/171
Caveats with Generics
PECS
– Collections that produce and consume must just
use one type parameter
• Not legal to combine extends and super
Collection<Something>
144. 144/171
Caveats with Generics
Ambiguity between parameterised types
http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs
public class Example9 {
public static String f(List<String> list) {
System.out.println("strings");
return null;
}
public static Integer f(List<Integer> list) {
System.out.println("numbers");
return null;
}
public static void main(String[] args) {
f(Arrays.asList("asdf"));
f(Arrays.asList(123));
}
}
145. 145/171
Caveats with Generics
Ambiguity between parameterised types
http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs
public class Example9 {
public static String f(List<String> list) {
System.out.println("strings");
return null;
}
public static Integer f(List<Integer> list) {
System.out.println("numbers");
return null;
}
public static void main(String[] args) {
f(Arrays.asList("asdf"));
f(Arrays.asList(123));
}
}
Legality depends on compiler
• Eclipse 3.5 says yes
• Eclipse 3.6 says no
• Intellij 9 says yes
• Sun javac 1.6.0_20 says yes
• GCJ 4.4.3 says yes
• GWT compiler says yes
• Crowd says no
146. 146/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
147. 147/171
Reflecting on Generics
Java generics use type erasure
– (Most) Type parameters / arguments are erased
at compile-time and exist at run-time only as
annotations
– Ensure backward-compatibility with pre-generic
Java code
– Limit access to type parameters / arguments
using reflection
148. 148/171
Caveats with Generics
Type-safe use of getClass()
http://stackoverflow.com/questions/11060491/
is-there-a-clean-way-to-assign-the-class-of-a-generic-type-to-a-variable
class Example11A {
}
public class Example11 {
public static void main(final String[] args) {
final Example11A anA1 = new Example11A();
final Class<Example11A> anA1Class =
(Class<Example11A>) anA1.getClass();
System.out.println(anA1Class);
final Example11A anA2 = new Example11A();
final Class<? extends Example11A> anA2Class = anA2.getClass();
System.out.println(anA2Class);
}
}
149. 149/171
Caveats with Generics
Type-safe use of getClass()
http://stackoverflow.com/questions/11060491/
is-there-a-clean-way-to-assign-the-class-of-a-generic-type-to-a-variable
class Example11A {
}
public class Example11 {
public static void main(final String[] args) {
final Example11A anA1 = new Example11A();
final Class<Example11A> anA1Class =
(Class<Example11A>) anA1.getClass();
System.out.println(anA1Class);
final Example11A anA2 = new Example11A();
final Class<? extends Example11A> anA2Class = anA2.getClass();
System.out.println(anA2Class);
}
}
Type safety: Unchecked cast from
Class<capture#1-of ?
extends Example11A> to
Class<Example11A>
150. 150/171
Caveats with Generics
Type-safe use of getClass()
http://stackoverflow.com/questions/11060491/
is-there-a-clean-way-to-assign-the-class-of-a-generic-type-to-a-variable
class Example11A {
}
public class Example11 {
public static void main(final String[] args) {
final Example11A anA1 = new Example11A();
final Class<Example11A> anA1Class =
(Class<Example11A>) anA1.getClass();
System.out.println(anA1Class);
final Example11A anA2 = new Example11A();
final Class<? extends Example11A> anA2Class = anA2.getClass();
System.out.println(anA2Class);
}
}
Type safety: Unchecked cast from
Class<capture#1-of ?
extends Example11A> to
Class<Example11A>
No warning
151. 151/171
Caveats with Generics
Type-safe use of getClass()
class MyList extends ArrayList<Integer> {
}
public class Example11 {
public static void main(final String[] args) {
final List<Integer> list1 = new ArrayList<Integer>();
final Class<List<Integer>> list1Class =
(Class<List<Integer>>) list1.getClass();
System.out.println(list1Class);
final MyList list2 = new MyList();
Class<? extends List<? extends Integer>> list2Class = list2.getClass();
System.out.println(list2Class);
}
}
http://stackoverflow.com/questions/11060491/
is-there-a-clean-way-to-assign-the-class-of-a-generic-type-to-a-variable
152. 152/171
Caveats with Generics
Type-safe use of getClass()
class MyList extends ArrayList<Integer> {
}
public class Example11 {
public static void main(final String[] args) {
final List<Integer> list1 = new ArrayList<Integer>();
final Class<List<Integer>> list1Class =
(Class<List<Integer>>) list1.getClass();
System.out.println(list1Class);
final MyList list2 = new MyList();
Class<? extends List<? extends Integer>> list2Class = list2.getClass();
System.out.println(list2Class);
}
}
Type safety: Unchecked cast from
Class<capture#4-of ? extends
List> to Class<List<Integer>>
http://stackoverflow.com/questions/11060491/
is-there-a-clean-way-to-assign-the-class-of-a-generic-type-to-a-variable
153. 153/171
Caveats with Generics
Type-safe use of getClass()
class MyList extends ArrayList<Integer> {
}
public class Example11 {
public static void main(final String[] args) {
final List<Integer> list1 = new ArrayList<Integer>();
final Class<List<Integer>> list1Class =
(Class<List<Integer>>) list1.getClass();
System.out.println(list1Class);
final MyList list2 = new MyList();
Class<? extends List<? extends Integer>> list2Class = list2.getClass();
System.out.println(list2Class);
}
}
Type safety: Unchecked cast from
Class<capture#4-of ? extends
List> to Class<List<Integer>>
No warninghttp://stackoverflow.com/questions/11060491/
is-there-a-clean-way-to-assign-the-class-of-a-generic-type-to-a-variable
154. 154/171
Caveats with Generics
Use of newInstance()
http://stackoverflow.com/questions/2592642/type-safety-unchecked-cast-from-object
class Example10A {
}
public class Example10 {
public static void main(final String[] args) {
final Class<Example10A> clazz1 = Example10A.class;
final Example10A anA1 = clazz1.newInstance();
System.out.println(anA1);
final Class<?> clazz2 = Class.forName(
"net.ptidej.generics.java.Example9A");
final Example10A anA2 = (Example10A) clazz2.newInstance();
System.out.println(anA2);
}
}
155. 155/171
Caveats with Generics
Obtaining the type of a type parameter
– Due to type erasure
• Type parameters are kept as annotations
• Type arguments disappear
Except for anonymous/local classes!
http://stackoverflow.com/questions/1901164/
get-type-of-a-generic-parameter-in-java-with-reflection
156. 156/171
Caveats with Generics
Obtaining the type of a type parameter
public final class Voodoo0 extends TestCase {
public static void chill(final List<?> aListWithSomeType) {
CommonTest.assertNotEqualAsExpected(
aListWithSomeType,
SpiderManVoodoo0.class);
}
public static void main(String... args) {
Voodoo0.chill(new ArrayList<SpiderManVoodoo0>());
}
public void test() {
Voodoo0.main(new String[0]);
}
}
class SpiderManVoodoo0 {
}
157. 157/171
Caveats with Generics
Obtaining the type of a type parameter
public final class Voodoo0 extends TestCase {
public static void chill(final List<?> aListWithSomeType) {
CommonTest.assertNotEqualAsExpected(
aListWithSomeType,
SpiderManVoodoo0.class);
}
public static void main(String... args) {
Voodoo0.chill(new ArrayList<SpiderManVoodoo0>());
}
public void test() {
Voodoo0.main(new String[0]);
}
}
class SpiderManVoodoo0 {
}
158. 158/171
Caveats with Generics
Obtaining the type of a type parameter
public static void main(java.lang.String...);
flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=2, locals=1, args_size=1
0: new #32 // class java/util/ArrayList
3: dup
4: invokespecial #34 // Method java/util/ArrayList."<init>":()V
7: invokestatic #35 // Method chill:(Ljava/util/List;)V
10: return
LineNumberTable:
line 38: 0
line 39: 10
LocalVariableTable:
Start Length Slot Name Signature
0 11 0 args [Ljava/lang/String;
159. 159/171
Caveats with Generics
Obtaining the type of a type parameter
public final class Voodoo1 extends TestCase {
public static void chill(final List<?> aListWithSomeType) {
CommonTest.assertNotEqualAsExpected(
aListWithSomeType,
SpiderManVoodoo1.class);
}
public static void main(String... args) {
Voodoo1.chill(new ArrayList<SpiderManVoodoo1>() {});
}
public void test() {
Voodoo1.main(new String[0]);
}
}
class SpiderManVoodoo1 {
}
160. 160/171
Caveats with Generics
Obtaining the type of a type parameter
public final class Voodoo1 extends TestCase {
public static void chill(final List<?> aListWithSomeType) {
CommonTest.assertNotEqualAsExpected(
aListWithSomeType,
SpiderManVoodoo1.class);
}
public static void main(String... args) {
Voodoo1.chill(new ArrayList<SpiderManVoodoo1>() {});
}
public void test() {
Voodoo1.main(new String[0]);
}
}
class SpiderManVoodoo1 {
}
161. 161/171
Caveats with Generics
Obtaining the type of a type parameter
public final class Voodoo1 extends TestCase {
public static void chill(final List<?> aListWithSomeType) {
CommonTest.assertNotEqualAsExpected(
aListWithSomeType,
SpiderManVoodoo1.class);
}
public static void main(String... args) {
Voodoo1.chill(new ArrayList<SpiderManVoodoo1>() {});
}
public void test() {
Voodoo1.main(new String[0]);
}
}
class SpiderManVoodoo1 {
}
162. 162/171
Caveats with Generics
Obtaining the type of a type parameter
public final class Voodoo1 extends TestCase {
public static void chill(final List<?> aListWithSomeType) {
CommonTest.assertNotEqualAsExpected(
aListWithSomeType,
SpiderManVoodoo1.class);
}
public static void main(String... args) {
Voodoo1.chill(new ArrayList<SpiderManVoodoo1>() {});
}
public void test() {
Voodoo1.main(new String[0]);
}
}
class SpiderManVoodoo1 {
}
Anonymous/local class
stores types information
163. 163/171
Caveats with Generics
Obtaining the type of a type parameter
public static void main(java.lang.String...);
flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=2, locals=1, args_size=1
0: new #32 // class net/ptidej/generics/java/erasure/Voodoo1$1
3: dup
4: invokespecial #34 // Method net/ptidej/generics/java/erasure/Voodoo1$1."<init>":()V
7: invokestatic #35 // Method chill:(Ljava/util/List;)V
10: return
LineNumberTable:
line 38: 0
line 41: 10
LocalVariableTable:
Start Length Slot Name Signature
0 11 0 args [Ljava/lang/String;
164. 164/171
Caveats with Generics
Obtaining the type of a type parameter
public static void main(java.lang.String...);
flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=2, locals=1, args_size=1
0: new #32 // class net/ptidej/generics/java/erasure/Voodoo1$1
3: dup
4: invokespecial #34 // Method net/ptidej/generics/java/erasure/Voodoo1$1."<init>":()V
7: invokestatic #35 // Method chill:(Ljava/util/List;)V
10: return
LineNumberTable:
line 38: 0
line 41: 10
LocalVariableTable:
Start Length Slot Name Signature
0 11 0 args [Ljava/lang/String;
165. 165/171
Caveats with Generics
Obtaining the type of a type parameter
// Compiled from Voodoo1.java (version 1.7 : 51.0, super bit)
// Signature: Ljava/util/ArrayList<Lca/polymtl/ptidej/generics/java/erasure/SpiderManVoodoo1;>;
class net.ptidej.generics.java.erasure.Voodoo1$1 extends java.util.ArrayList {
...
// Method descriptor #11 ()V
// Stack: 1, Locals: 1
Voodoo1$1();
0 aload_0 [this]
1 invokespecial java.util.ArrayList() [13]
4 return
Line numbers:
[pc: 0, line: 38]
[pc: 4, line: 1]
Local variable table:
[pc: 0, pc: 5] local: this index: 0 type: new ....java.erasure.Voodoo1(){}
...
}
166. 166/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
168. 168/171
Conclusion
Scenario 1: you want to enforce type safety
for containers and remove the need for
typecasts when using these containers
Scenario 2: you want to build generic
algorithms that work on several types of
(possible unrelated) things
169. 169/171
Conclusion
Easy to use in simple cases
Some caveats, though
Can be very tricky is corner cases
– Use them sparingly and purposefully
170. 170/171
Outline
History
Problem
Special Case
General Definitions
Generics Definitions
– Parametric
Polymorphism
– Other Bounded
Parametric
Polymorphisms
When to Use Generics
How to Use Generics
Caveats with Generics
Reflecting on Generics
Conclusion
Few References
171. 171/171
Outline
In no particular order
– http://en.wikipedia.org/wiki/Generics_in_Java
– http://www.angelikalanger.com/GenericsFAQ/FAQ
Sections/TechnicalDetails.html#FAQ502
– http://www.uio.no/studier/emner/matnat/ifi/INF3110/h05/
lysark/Types.pdf
– http://www.slideshare.net/SFilipp/java-puzzle-167104
– http://www.jquantlib.org/index.php/Using_TypeTokens_
to_retrieve_generic_parameters#Anonymous_classes
– http://www.clear.rice.edu/comp310/JavaResources/ generics/
– http://gafter.blogspot.kr/2006/12/super-type-tokens.html