SlideShare une entreprise Scribd logo
1  sur  64
GENERIC TYPES IN
JAVA
AGENDA
General information
Bounds and Restrictions
Erasure
Heap pollution
Java8
Lambda
Spring
Generics Stream API
HOW GOOD YOU ARE AT
GENERICS?
<R> Strudel<R> loop(Function<? super T,? extends R> mapper)<R> Stream<R> map(Function<? super T,? extends R> mapper)
A generic type is a generic class or interface that
is parameterized over types.
Code that uses generics has many benefits over
non-generic code:
Stronger type checks at compile time.
Elimination of casts.
Enabling programmers to implement
generic algorithms.
public class Box {
private Object object;
public void set(Object o){
this.object = o;
}
public Object get() {
return object;
}
}
public class Box<T> {
private T t;
public void set(T t)
{ this.t = t; }
public T get()
{ return t; }
}
As you can see, all occurrences of Object are replaced by T. A type
variable can be any non-primitive type you specify: any class type,
any interface type, any array type, or even another type variable.
Simple Example
public class Test {
public static void main(String[] args) {
BoxPrinter value1 = new BoxPrinter(new Integer(10));
System.out.println(value1);
Integer intValue1 = (Integer) value1.getValue();
BoxPrinter value2 = new BoxPrinter("Hello world");
System.out.println(value2);
// Ooops ...
Integer intValue2 = (Integer) value2.getValue();
}
}
class BoxPrinter {
private Object val;
public BoxPrinter(Object arg) {
val = arg;
}
public String toString() {
return "{" + val + "}";
}
public Object getValue() {
return val;
}
}
public class Test {
public static void main(String[] args) {
BoxPrinter<Integer> value1 = new BoxPrinter<Integer>(new Integer(10));
System.out.println(value1);
Integer intValue1 = value1.getValue();
BoxPrinter<String> value2 = new BoxPrinter<String>("Hello world");
System.out.println(value2);
// Compile error
Integer intValue2 = value2.getValue();
}
}
class BoxPrinter<T> {
private T val;
public BoxPrinter(T arg) {
val = arg;
}
public String toString() {
return "{" + val + "}";
}
public T getValue() {
return val;
}
}
Naming Conventions
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections
Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
Integer i = 127;
Class<Integer> c = i.getClass(); //compile error
Generic Methods
Generic methods are methods that introduce their own type parameters. This
is similar to declaring a generic type, but the type parameter's scope is
limited to the method where it is declared.
Static and non-static generic methods are allowed, as well as
generic class constructors.
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
GENERIC GENERAL RESTRICTIONS
• Cannot Instantiate Generic Types with Primitive Types
• Cannot Create Instances of Type Parameters
• Cannot Declare Static Fields Whose Types are Type
Parameters
• Cannot Use Casts or instanceof With Parameterized
Types
• Cannot Create Arrays of Parameterized Types
• Cannot Create, Catch, or Throw Objects of Parameterized
Types
• Cannot Overload a Method Where the Formal Parameter
Types of Each Overload Erase to the Same Raw Type
Cannot Create Instances of Type Parameters
You cannot create an instance of a type parameter. For example, the
following code causes a compile-time error:
But, You can always use Reflection API
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}
Cannot Use Casts or instanceof with Parameterized Types
Because the Java compiler erases all type parameters in generic code, you
cannot verify which parameterized type for a generic type is being used at
runtime:
Cannot Create Arrays of Parameterized Types
You cannot create arrays of parameterized types. For example, the following
code does not compile:
public static <E> void doSmth(List<E> list) {
if (list instanceof ArrayList<Integer>) { // compile-time
error
// some logic
}
}
List<Integer>[] arrayOfLists = new List<Integer>[2]; // compile-
time error
Cannot Create, Catch, or Throw Objects of Parameterized Types
A generic class cannot extend the Throwable class directly or indirectly.
// Extends Throwable indirectly
// Extends Throwable directly
A method cannot catch an instance of a type parameter:
You can, however, use a type parameter in a throws clause:
class MathException<T> extends Exception // compile-time error
class QueueFullException<T> extends Throwable // compile-time error
public static <T extends Exception, J> void execute(List<J> jobs) {
try {
for (J job : jobs);
} catch (T e) { // compile-time error
}
}
class Parser<T extends Exception> {
public void parse(File file) throws T { // OK
}
public class Quiz5<T> {
public List<Integer> numbers() {
return Arrays.asList(1,2);
}
public static void main(String[] args) {
Quiz5 quiz = new Quiz5();
for (Integer i: quiz.numbers()) {
System.out.println(i);
}
}
}
// wtf?! this code is ok
// ClassCastException
// Compile Error
// NPE
//error here
incompatible types
TYPE
Generics were introduced to the Java language to provide
tighter type checks at compile time and to support generic
programming.
To implement generics, the Java compiler applies type
erasure.
public class Person implements Comparable<Person> {
private String name;
@Override
public int compareTo(Person o) {
return name.compareTo(o.name);
}
public int compareTo(Object o) {
return toString().compareTo(o.toString());
}
}
//compile error
// both methods have same erasure
ERASURE
class Box<T> {
private T value;
public Box (T t) {
this.value = t;
}
public T get() {
return value;
}
}
Box<Integer> box = new Box<>(10);
Integer i = box.get();
Box box = new Box (10);
Integer i = (Integer) box.get();
class Box {
private Object value;
public Box (Object t) {
this.value = t;
}
public Object get() {
return value;
}
}
//java compiles//we write
Bridge Methods
public class Person implements Comparable<Person> {
private String name;
@Override
public int compareTo(Person o) {
return name.compareTo(o.name);
}
public static void main(String[] args) {
Stream.of(Person.class.getDeclaredMethods()).
forEach(System.out::println);
}
}
public int Quiz4.Person.compareTo(java.lang.Object)
public int Quiz4.Person.compareTo(Quiz4.Person)
//Sout
//wtf? o.O
public interface Comparable<T> {
int CompareTo (T t)
}
public interface Comparable {
int CompareTo (Object o)
}
public class Person implements Comparable<Person> {
@Override
public int compareTo(Person o) {
return 0;
}
}
//isSynthetic()
public int compareTo(Object o) {
return compareTo((Person) o);
}
ArrayList - sometimes things are different from what you see
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
. . .
private E[] elementData;
private int DEFAULT_CAPACITY = 10;
. . .
public ArrayList() {
elementData = new E[DEFAULT_CAPACITY];
}
. . .
}
Aww, you fool! It’s not
going to work!
Aww, you fool! It’s not
going to work!
Type parameter «E» cannot
be instantiated directly
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
private E[] elementData;
private int DEFAULT_CAPACITY = 10;
public ArrayList() {
elementData = (E[]) new Object[DEFAULT_CAPACITY];
}
. . .
}
As I said in «Effective
Java» - casts are
good.
Well done, my boy!
As I said in «Effective
Java» - casts are
good.
Well done, my boy!
Bounds || Restrictions
public class Box <T> {
private T t;
public <U extends Number> void inspect(U u){
System.out.println("T: " +
t.getClass().getName());
System.out.println("U: " +
u.getClass().getName());
}
public static void main(String[] args) {
Box<Integer> integerBox = new
Box<Integer>();
integerBox.set(new Integer(10));
integerBox.inspect("some text");
// error: this is still String!
}
}
class NaturalNumber<T extends Integer> {
private T n;
public NaturalNumber(T n) {
this.n = n;
}
public boolean isEven() {
return n.intValue() % 2 == 0;
}
//The isEven method invokes
//the intValue method defined in
//the Integer class through n.
}
class D <T extends A & B & C> // we can do multiple bounds, BUT …class D <T extends A & B & C> // we can do multiple bounds, BUT …
Type Inference
Type inference is a Java compiler's ability to look at each
method invocation and corresponding declaration to
determine the type argument (or arguments) that make the
invocation applicable.
static <T> T pick(T a1, T a2) { return a2; }
Serializable s = pick("d", new ArrayList<String>());
Target Types
The Java compiler takes advantage of target typing to infer the
type parameters of a generic method invocation. The target
type of an expression is the data type that the Java compiler
expects depending on where the expression appears.
static <T> List<T> emptyList();
processStringList(Collections.emptyList());processStringList(Collections.emptyList());
void processStringList(List<String> stringList)
{
/* some logic */
}
List<Object> cannot be
converted to List<String>
ClassCastException
Incompatible types
No errors or exceptions//JDK7
WILDCARDS
Upper Bounded WildCards
To write the method that works on lists of Number and the subtypes of Number,
such as Integer, Double, and Float, you would specify List<? extends Number>.
public static void process(List<?
extends Foo> list) { }
public static void process(List<? extends Foo>
list) {
for (Foo elem : list) {
// ...
}
}
public static double sumOfList(List<?
extends Number> list) {
double s = 0.0;
for (Number n : list)
s += n.doubleValue();
return s;
}
List<Integer> li = Arrays.asList(1, 2, 3);
System.out.println("sum = " + sumOfList(li)); //sum = 6.0
List<Double> ld = Arrays.asList(1.2, 2.3, 3.5);
System.out.println("sum = " + sumOfList(ld)); //sum = 7.0
Story about no one, experimental
class Foo<T extends Cloneable> {
public void doSomething(T param) {
T copy = (T) param.clone();
}
}
3. this code is perfect,
don’t talk shit
2. incompatible types
1. ClassCastException
4. none above
Unbounded Wildcard
The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of
Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they are
not subtypes of List<Object>. To write a generic printList method, use List<?>:
Because for any concrete type A, List<A> is a subtype of List<?>, you can use printList to print a list of
any type:
public static void printList(List<Object> list) {
for (Object elem : list)
System.out.println(elem + " ");
System.out.println();
}
public static void printList(List<?> list) {
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}
List<Integer> li = Arrays.asList(1, 2, 3);
List<String> ls = Arrays.asList("one", "two", "three");
printList(li);
printList(ls);
Lower Bounded Wildcards
You can specify an upper bound for a wildcard, or
you can specify a lower bound, but you cannot
specify both.
<? super X>
As for key word <? extends> You can use <? super>
to specify any base class or interface of X, and X itself
List<? super Integer> list
List<? extends Number> numbers = new ArrayList<>();
List<? super Number> numbers = new ArrayList<>();
What we can add to the following
collections via numbers.add() ?
Integer, Double, Number, Long
Object, Number
List<?> list = new ArrayList<>();
anything?
null
null
all that ? extend Number
List <? extends Number> list = new ArrayList<>();
list.add(); <- null
List <? extends Number> list = …
list = new ArrayList<Number>;
list = new ArrayList<Integer>;
list = new ArrayList<Long>;
//what compiler sees
//what possibly can come
List <? super Number> list = new ArrayList<>();
list.add(); <- all that ? extends Number
List <? super Number> list = …
//what compiler sees
list = ArrayList<Object>();
list = ArrayList<Number>();
//what possibly can come
public class MindBlown <T extends MindBlown<T>>
WTF is it? An infinite recursion? How this gonna work?
public class Enum <E extends Enum<E>>
WHY?
1. The type parameter E is used in various methods of Enum, such as compareTo()
or getDeclaringClass()
2. Classes that are type arguments to Enum must themselves be subtypes of Enum,
so you can't declare a class X to extend Enum<Integer>
3. Any class that extends Enum must pass itself as the type parameter. You cannot
declare X to extend Enum<Y>, even if Y extends Enum.
public void run(List<String>...list) {
}
//WARNING: possible heap pollution
HEAP
List<String> = List<Integer>
Number [] numbers = new Integer [10];
List<Number> numberList = new ArrayList<Integer>();
// compile error
numbers[0] = 9.7d; //ArrayStoreException
!Arrays are co-variant, Generics - invariant!
IT’S PUZZLER TIME!!!
Story about one girl, who loved Interfaces 
public static void main(String[] args) {
String stringIsFinalClass = newlist();
}
private static <A extends List> A newList() {
return (A) new ArrayList<>();
}
Cannot infer arguments
Incompatible types
Runtime error
I once wright code like this
Story about one dev, who loved checked Exceptions 
public class B {
public static <T> T foo() {
try {
return (T) new Integer(42);
} catch (ClassCastException e) {
return (T) "ArtClub";
}
}
public static void main(String[] args) {
System.out.println(B.<String>foo());
}
}
Compile error
Runtime error
print 42
print ArtClub
ClassCastException
Story about one boy, who trust compilers
List<Integer> integers = new ArrayList<Integer>();
List list = integers;
List<Number> numbers = list;
numbers.add(9.78d);
9.78
ClassCastException
Compile Error
9
System.out.println(numbers.get(0));
System.out.println(integers.get(0));
Story about one philosopher , 
who loved to focus
Set<Number> set = new TreeSet<>();
set.add(1);
set.add(1L);
set.add(1.00);
System.out.println(set.size());
A. 3 B. Compile error
C. 2 D. Runtime error
Story about one Andriy, who loved arrays
public static void main(String[] args) {
setFirst(new String[10],
}
1.incompatible types
2.ClassCastException
3.cannot infer arguments
4.i don’t believe generics anymore
//JDK 7
1);
new Integer(1));
static <T> void setFirst(T[] ar, T s) {
ar[0] = s;
}
// ну ок
How we fix it?
static <T, S extends T> void setFirst(T[] ar, S s) {
ar[0] = s;
}
public static void main(String[] args) {
setFirst(new String[10], new Integer(1));
}
// compile error
//JDK8
// ArrayStoreException
Story about one Troll, who lives under bridge
abstract class DefaultList<T> {
abstract void add(T ... elements);
void addNotNull(T...elements) {
for (T element : elements) {
if (element != null);
add(element);
}
}
}
public class ConcreateList extends DefaultList<String> {
private final List<String> list = new ArrayList<>();
@Override
void add(String... elements) {
list.addAll(Arrays.asList(elements));
}
@Override
public String toString() {
return list.toString();
}
public static void main(String[] args) {
DefaultList<String> stringList = new ConcreateList();
stringList.addNotNull("null", null);
System.out.println(stringList);
}
}
1. «null»
2. «null», «null»
3. Compile error
4. Runtime error
// error here
// error here
// error here
Story about one gayse, who wants ofigenno
public class Compressor<T> {
String compress(Collection<?> obj) {
String s = "";
for (Object o : obj)
s += obj.toString();
return s;
}
int compress(List<Integer> list) {
int result = 0;
for (int i: list)
result+=i;
return result;
}
public static void main(String[] args) {
List<String> list = Arrays.asList("1","2","3");
System.out.println(new Compressor().compress(list));
}
}
1. Compile error
2. Runtime error
3. 6
4. 123
// classCastException
PECS (Producer - extends, Consumer - super)
If a parametrized type represents a T
producer -
use <? extends T>;
If a parametrized type represents a T
consumer -
use <? super T>;
Joshua Bloch
public static <T> T max(Collection<? extends T> coll,
Comparator<? super T> comp);
Integer i = 127;
Class<Integer> c = i.getClass(); //compile error
Why this isn’t working?class Object {
Class<?> getClass();
}
class Number {
Class<Number>
getClass();
}
class Integer {
Class<Integer>
getClass();
1, 2, 3, 1440988108
1, 2, 3, 23 nov 2016 19:56:00:00:00
ClassCastException
Compile error
List<Long> list = new ArrayList<>();
list.add(1L);
list.add(2L);
list.add(3L);
Date now = new Date();
list.add(now);
for (def node: list) {
System.out.println(node);
}
Q/A?
https://www.facebook.com/andrew.petryk
@ipreferespresso
www.linkedin.com/in/andrew-petryk

Contenu connexe

Tendances

Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
도메인 주도 설계 - 6장 도메인 객체의 생명주기
도메인 주도 설계 - 6장 도메인 객체의 생명주기도메인 주도 설계 - 6장 도메인 객체의 생명주기
도메인 주도 설계 - 6장 도메인 객체의 생명주기JangHyuk You
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean ArchitectureMattia Battiston
 
Drools and jBPM 6 Overview
Drools and jBPM 6 OverviewDrools and jBPM 6 Overview
Drools and jBPM 6 OverviewMark Proctor
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
From 'dotnet run' to 'hello world'
From 'dotnet run' to 'hello world'From 'dotnet run' to 'hello world'
From 'dotnet run' to 'hello world'Matt Warren
 
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration수홍 이
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default MethodsHaim Michael
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesLauren Yew
 
QA Fest 2019. Андрей Солнцев. Selenide для профи
QA Fest 2019. Андрей Солнцев. Selenide для профиQA Fest 2019. Андрей Солнцев. Selenide для профи
QA Fest 2019. Андрей Солнцев. Selenide для профиQAFest
 
LinkedList vs ArrayList in Java | Edureka
LinkedList vs ArrayList in Java | EdurekaLinkedList vs ArrayList in Java | Edureka
LinkedList vs ArrayList in Java | EdurekaEdureka!
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and AnnotationsAnuj Singh Rajput
 
아꿈사 DDD(Domain-Driven Design) 5장 소프트웨어에서 표현되는 모델
아꿈사 DDD(Domain-Driven Design) 5장 소프트웨어에서 표현되는 모델아꿈사 DDD(Domain-Driven Design) 5장 소프트웨어에서 표현되는 모델
아꿈사 DDD(Domain-Driven Design) 5장 소프트웨어에서 표현되는 모델명환 안
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 

Tendances (20)

Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
도메인 주도 설계 - 6장 도메인 객체의 생명주기
도메인 주도 설계 - 6장 도메인 객체의 생명주기도메인 주도 설계 - 6장 도메인 객체의 생명주기
도메인 주도 설계 - 6장 도메인 객체의 생명주기
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
Introduction à JPA (Java Persistence API )
Introduction à JPA  (Java Persistence API )Introduction à JPA  (Java Persistence API )
Introduction à JPA (Java Persistence API )
 
Drools and jBPM 6 Overview
Drools and jBPM 6 OverviewDrools and jBPM 6 Overview
Drools and jBPM 6 Overview
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
From 'dotnet run' to 'hello world'
From 'dotnet run' to 'hello world'From 'dotnet run' to 'hello world'
From 'dotnet run' to 'hello world'
 
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
 
QA Fest 2019. Андрей Солнцев. Selenide для профи
QA Fest 2019. Андрей Солнцев. Selenide для профиQA Fest 2019. Андрей Солнцев. Selenide для профи
QA Fest 2019. Андрей Солнцев. Selenide для профи
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
LinkedList vs ArrayList in Java | Edureka
LinkedList vs ArrayList in Java | EdurekaLinkedList vs ArrayList in Java | Edureka
LinkedList vs ArrayList in Java | Edureka
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
아꿈사 DDD(Domain-Driven Design) 5장 소프트웨어에서 표현되는 모델
아꿈사 DDD(Domain-Driven Design) 5장 소프트웨어에서 표현되는 모델아꿈사 DDD(Domain-Driven Design) 5장 소프트웨어에서 표현되는 모델
아꿈사 DDD(Domain-Driven Design) 5장 소프트웨어에서 표현되는 모델
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 

En vedette

Community of Scholars Remake_12 page version
Community of Scholars Remake_12 page versionCommunity of Scholars Remake_12 page version
Community of Scholars Remake_12 page versionJiaorui Jiang
 
cần bán đồng hồ casio dây inox
cần bán đồng hồ casio dây inoxcần bán đồng hồ casio dây inox
cần bán đồng hồ casio dây inoxjoellen640
 
Obligaciones civiles y comerciales
Obligaciones civiles y comercialesObligaciones civiles y comerciales
Obligaciones civiles y comercialesALI, unico Unico
 
Lawyer in Vietnam Oliver Massmann EXPATS WITH DEGREES AND 3 YEARS EXPERIENCE ...
Lawyer in Vietnam Oliver Massmann EXPATS WITH DEGREES AND 3 YEARS EXPERIENCE ...Lawyer in Vietnam Oliver Massmann EXPATS WITH DEGREES AND 3 YEARS EXPERIENCE ...
Lawyer in Vietnam Oliver Massmann EXPATS WITH DEGREES AND 3 YEARS EXPERIENCE ...Dr. Oliver Massmann
 
Pedagogo na área empresarial
Pedagogo na área empresarialPedagogo na área empresarial
Pedagogo na área empresarialLeandro Oliveira
 
How MOOCs Boost Student Mobility and Increase Cross-Institutional Programmes ...
How MOOCs Boost Student Mobility and Increase Cross-Institutional Programmes ...How MOOCs Boost Student Mobility and Increase Cross-Institutional Programmes ...
How MOOCs Boost Student Mobility and Increase Cross-Institutional Programmes ...EADTU
 
Ebook En Sams Data Structures & Algorithms In Java
Ebook   En  Sams   Data Structures & Algorithms In JavaEbook   En  Sams   Data Structures & Algorithms In Java
Ebook En Sams Data Structures & Algorithms In JavaAldo Quelopana
 
TCIOceania16 Boosting the Internationalisation and Competitiveness of Danish ...
TCIOceania16 Boosting the Internationalisation and Competitiveness of Danish ...TCIOceania16 Boosting the Internationalisation and Competitiveness of Danish ...
TCIOceania16 Boosting the Internationalisation and Competitiveness of Danish ...TCI Network
 
[FR] Introduction à l'interface conversationnelle avec Amazon Echo
[FR] Introduction à l'interface conversationnelle avec Amazon Echo[FR] Introduction à l'interface conversationnelle avec Amazon Echo
[FR] Introduction à l'interface conversationnelle avec Amazon EchoAlexandre Tostivint ☁️
 

En vedette (17)

goto java; (Jfokus)
goto java; (Jfokus)goto java; (Jfokus)
goto java; (Jfokus)
 
Community of Scholars Remake_12 page version
Community of Scholars Remake_12 page versionCommunity of Scholars Remake_12 page version
Community of Scholars Remake_12 page version
 
Presentación PsicoAgora Consultores
Presentación PsicoAgora ConsultoresPresentación PsicoAgora Consultores
Presentación PsicoAgora Consultores
 
Diversos
DiversosDiversos
Diversos
 
contract for parents
contract for parentscontract for parents
contract for parents
 
Mapa mental
Mapa mentalMapa mental
Mapa mental
 
cần bán đồng hồ casio dây inox
cần bán đồng hồ casio dây inoxcần bán đồng hồ casio dây inox
cần bán đồng hồ casio dây inox
 
Obligaciones civiles y comerciales
Obligaciones civiles y comercialesObligaciones civiles y comerciales
Obligaciones civiles y comerciales
 
Lawyer in Vietnam Oliver Massmann EXPATS WITH DEGREES AND 3 YEARS EXPERIENCE ...
Lawyer in Vietnam Oliver Massmann EXPATS WITH DEGREES AND 3 YEARS EXPERIENCE ...Lawyer in Vietnam Oliver Massmann EXPATS WITH DEGREES AND 3 YEARS EXPERIENCE ...
Lawyer in Vietnam Oliver Massmann EXPATS WITH DEGREES AND 3 YEARS EXPERIENCE ...
 
Pedagogo na área empresarial
Pedagogo na área empresarialPedagogo na área empresarial
Pedagogo na área empresarial
 
Five perspectives
Five perspectivesFive perspectives
Five perspectives
 
How MOOCs Boost Student Mobility and Increase Cross-Institutional Programmes ...
How MOOCs Boost Student Mobility and Increase Cross-Institutional Programmes ...How MOOCs Boost Student Mobility and Increase Cross-Institutional Programmes ...
How MOOCs Boost Student Mobility and Increase Cross-Institutional Programmes ...
 
Déplacements dans Ivry confluences
Déplacements dans Ivry confluencesDéplacements dans Ivry confluences
Déplacements dans Ivry confluences
 
Drivers for 5G
Drivers for 5GDrivers for 5G
Drivers for 5G
 
Ebook En Sams Data Structures & Algorithms In Java
Ebook   En  Sams   Data Structures & Algorithms In JavaEbook   En  Sams   Data Structures & Algorithms In Java
Ebook En Sams Data Structures & Algorithms In Java
 
TCIOceania16 Boosting the Internationalisation and Competitiveness of Danish ...
TCIOceania16 Boosting the Internationalisation and Competitiveness of Danish ...TCIOceania16 Boosting the Internationalisation and Competitiveness of Danish ...
TCIOceania16 Boosting the Internationalisation and Competitiveness of Danish ...
 
[FR] Introduction à l'interface conversationnelle avec Amazon Echo
[FR] Introduction à l'interface conversationnelle avec Amazon Echo[FR] Introduction à l'interface conversationnelle avec Amazon Echo
[FR] Introduction à l'interface conversationnelle avec Amazon Echo
 

Similaire à Generic Types in Java (for ArtClub @ArtBrains Software) (20)

Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Java generics
Java genericsJava generics
Java generics
 
Generics
GenericsGenerics
Generics
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
Java 2
Java   2Java   2
Java 2
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
Java Generics
Java GenericsJava Generics
Java Generics
 

Dernier

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Dernier (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

Generic Types in Java (for ArtClub @ArtBrains Software)

  • 2. AGENDA General information Bounds and Restrictions Erasure Heap pollution
  • 4. HOW GOOD YOU ARE AT GENERICS? <R> Strudel<R> loop(Function<? super T,? extends R> mapper)<R> Stream<R> map(Function<? super T,? extends R> mapper)
  • 5. A generic type is a generic class or interface that is parameterized over types. Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. Elimination of casts. Enabling programmers to implement generic algorithms.
  • 6. public class Box { private Object object; public void set(Object o){ this.object = o; } public Object get() { return object; } } public class Box<T> { private T t; public void set(T t) { this.t = t; } public T get() { return t; } } As you can see, all occurrences of Object are replaced by T. A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable. Simple Example
  • 7. public class Test { public static void main(String[] args) { BoxPrinter value1 = new BoxPrinter(new Integer(10)); System.out.println(value1); Integer intValue1 = (Integer) value1.getValue(); BoxPrinter value2 = new BoxPrinter("Hello world"); System.out.println(value2); // Ooops ... Integer intValue2 = (Integer) value2.getValue(); } } class BoxPrinter { private Object val; public BoxPrinter(Object arg) { val = arg; } public String toString() { return "{" + val + "}"; } public Object getValue() { return val; } }
  • 8. public class Test { public static void main(String[] args) { BoxPrinter<Integer> value1 = new BoxPrinter<Integer>(new Integer(10)); System.out.println(value1); Integer intValue1 = value1.getValue(); BoxPrinter<String> value2 = new BoxPrinter<String>("Hello world"); System.out.println(value2); // Compile error Integer intValue2 = value2.getValue(); } } class BoxPrinter<T> { private T val; public BoxPrinter(T arg) { val = arg; } public String toString() { return "{" + val + "}"; } public T getValue() { return val; } }
  • 9. Naming Conventions The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th types
  • 10. Integer i = 127; Class<Integer> c = i.getClass(); //compile error
  • 11. Generic Methods Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors. public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) { return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()); }
  • 12. GENERIC GENERAL RESTRICTIONS • Cannot Instantiate Generic Types with Primitive Types • Cannot Create Instances of Type Parameters • Cannot Declare Static Fields Whose Types are Type Parameters • Cannot Use Casts or instanceof With Parameterized Types • Cannot Create Arrays of Parameterized Types • Cannot Create, Catch, or Throw Objects of Parameterized Types • Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type
  • 13. Cannot Create Instances of Type Parameters You cannot create an instance of a type parameter. For example, the following code causes a compile-time error: But, You can always use Reflection API public static <E> void append(List<E> list) { E elem = new E(); // compile-time error list.add(elem); } public static <E> void append(List<E> list, Class<E> cls) throws Exception { E elem = cls.newInstance(); // OK list.add(elem); }
  • 14. Cannot Use Casts or instanceof with Parameterized Types Because the Java compiler erases all type parameters in generic code, you cannot verify which parameterized type for a generic type is being used at runtime: Cannot Create Arrays of Parameterized Types You cannot create arrays of parameterized types. For example, the following code does not compile: public static <E> void doSmth(List<E> list) { if (list instanceof ArrayList<Integer>) { // compile-time error // some logic } } List<Integer>[] arrayOfLists = new List<Integer>[2]; // compile- time error
  • 15. Cannot Create, Catch, or Throw Objects of Parameterized Types A generic class cannot extend the Throwable class directly or indirectly. // Extends Throwable indirectly // Extends Throwable directly A method cannot catch an instance of a type parameter: You can, however, use a type parameter in a throws clause: class MathException<T> extends Exception // compile-time error class QueueFullException<T> extends Throwable // compile-time error public static <T extends Exception, J> void execute(List<J> jobs) { try { for (J job : jobs); } catch (T e) { // compile-time error } } class Parser<T extends Exception> { public void parse(File file) throws T { // OK }
  • 16. public class Quiz5<T> { public List<Integer> numbers() { return Arrays.asList(1,2); } public static void main(String[] args) { Quiz5 quiz = new Quiz5(); for (Integer i: quiz.numbers()) { System.out.println(i); } } } // wtf?! this code is ok // ClassCastException // Compile Error // NPE //error here incompatible types
  • 17. TYPE Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure.
  • 18. public class Person implements Comparable<Person> { private String name; @Override public int compareTo(Person o) { return name.compareTo(o.name); } public int compareTo(Object o) { return toString().compareTo(o.toString()); } } //compile error // both methods have same erasure ERASURE
  • 19. class Box<T> { private T value; public Box (T t) { this.value = t; } public T get() { return value; } } Box<Integer> box = new Box<>(10); Integer i = box.get(); Box box = new Box (10); Integer i = (Integer) box.get(); class Box { private Object value; public Box (Object t) { this.value = t; } public Object get() { return value; } } //java compiles//we write
  • 20. Bridge Methods public class Person implements Comparable<Person> { private String name; @Override public int compareTo(Person o) { return name.compareTo(o.name); } public static void main(String[] args) { Stream.of(Person.class.getDeclaredMethods()). forEach(System.out::println); } } public int Quiz4.Person.compareTo(java.lang.Object) public int Quiz4.Person.compareTo(Quiz4.Person) //Sout //wtf? o.O
  • 21. public interface Comparable<T> { int CompareTo (T t) } public interface Comparable { int CompareTo (Object o) } public class Person implements Comparable<Person> { @Override public int compareTo(Person o) { return 0; } } //isSynthetic() public int compareTo(Object o) { return compareTo((Person) o); }
  • 22. ArrayList - sometimes things are different from what you see public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { . . . private E[] elementData; private int DEFAULT_CAPACITY = 10; . . . public ArrayList() { elementData = new E[DEFAULT_CAPACITY]; } . . . } Aww, you fool! It’s not going to work! Aww, you fool! It’s not going to work! Type parameter «E» cannot be instantiated directly
  • 23. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private E[] elementData; private int DEFAULT_CAPACITY = 10; public ArrayList() { elementData = (E[]) new Object[DEFAULT_CAPACITY]; } . . . } As I said in «Effective Java» - casts are good. Well done, my boy! As I said in «Effective Java» - casts are good. Well done, my boy!
  • 24. Bounds || Restrictions public class Box <T> { private T t; public <U extends Number> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.set(new Integer(10)); integerBox.inspect("some text"); // error: this is still String! } } class NaturalNumber<T extends Integer> { private T n; public NaturalNumber(T n) { this.n = n; } public boolean isEven() { return n.intValue() % 2 == 0; } //The isEven method invokes //the intValue method defined in //the Integer class through n. } class D <T extends A & B & C> // we can do multiple bounds, BUT …class D <T extends A & B & C> // we can do multiple bounds, BUT …
  • 25. Type Inference Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. static <T> T pick(T a1, T a2) { return a2; } Serializable s = pick("d", new ArrayList<String>());
  • 26. Target Types The Java compiler takes advantage of target typing to infer the type parameters of a generic method invocation. The target type of an expression is the data type that the Java compiler expects depending on where the expression appears. static <T> List<T> emptyList(); processStringList(Collections.emptyList());processStringList(Collections.emptyList()); void processStringList(List<String> stringList) { /* some logic */ } List<Object> cannot be converted to List<String> ClassCastException Incompatible types No errors or exceptions//JDK7
  • 27.
  • 29. Upper Bounded WildCards To write the method that works on lists of Number and the subtypes of Number, such as Integer, Double, and Float, you would specify List<? extends Number>. public static void process(List<? extends Foo> list) { } public static void process(List<? extends Foo> list) { for (Foo elem : list) { // ... } } public static double sumOfList(List<? extends Number> list) { double s = 0.0; for (Number n : list) s += n.doubleValue(); return s; } List<Integer> li = Arrays.asList(1, 2, 3); System.out.println("sum = " + sumOfList(li)); //sum = 6.0 List<Double> ld = Arrays.asList(1.2, 2.3, 3.5); System.out.println("sum = " + sumOfList(ld)); //sum = 7.0
  • 30. Story about no one, experimental class Foo<T extends Cloneable> { public void doSomething(T param) { T copy = (T) param.clone(); } } 3. this code is perfect, don’t talk shit 2. incompatible types 1. ClassCastException 4. none above
  • 31. Unbounded Wildcard The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they are not subtypes of List<Object>. To write a generic printList method, use List<?>: Because for any concrete type A, List<A> is a subtype of List<?>, you can use printList to print a list of any type: public static void printList(List<Object> list) { for (Object elem : list) System.out.println(elem + " "); System.out.println(); } public static void printList(List<?> list) { for (Object elem: list) System.out.print(elem + " "); System.out.println(); } List<Integer> li = Arrays.asList(1, 2, 3); List<String> ls = Arrays.asList("one", "two", "three"); printList(li); printList(ls);
  • 32. Lower Bounded Wildcards You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both. <? super X> As for key word <? extends> You can use <? super> to specify any base class or interface of X, and X itself List<? super Integer> list
  • 33. List<? extends Number> numbers = new ArrayList<>(); List<? super Number> numbers = new ArrayList<>(); What we can add to the following collections via numbers.add() ? Integer, Double, Number, Long Object, Number List<?> list = new ArrayList<>(); anything? null null all that ? extend Number
  • 34. List <? extends Number> list = new ArrayList<>(); list.add(); <- null List <? extends Number> list = … list = new ArrayList<Number>; list = new ArrayList<Integer>; list = new ArrayList<Long>; //what compiler sees //what possibly can come
  • 35. List <? super Number> list = new ArrayList<>(); list.add(); <- all that ? extends Number List <? super Number> list = … //what compiler sees list = ArrayList<Object>(); list = ArrayList<Number>(); //what possibly can come
  • 36. public class MindBlown <T extends MindBlown<T>> WTF is it? An infinite recursion? How this gonna work? public class Enum <E extends Enum<E>> WHY? 1. The type parameter E is used in various methods of Enum, such as compareTo() or getDeclaringClass() 2. Classes that are type arguments to Enum must themselves be subtypes of Enum, so you can't declare a class X to extend Enum<Integer> 3. Any class that extends Enum must pass itself as the type parameter. You cannot declare X to extend Enum<Y>, even if Y extends Enum.
  • 37. public void run(List<String>...list) { } //WARNING: possible heap pollution HEAP List<String> = List<Integer>
  • 38. Number [] numbers = new Integer [10]; List<Number> numberList = new ArrayList<Integer>(); // compile error numbers[0] = 9.7d; //ArrayStoreException !Arrays are co-variant, Generics - invariant!
  • 41. public static void main(String[] args) { String stringIsFinalClass = newlist(); } private static <A extends List> A newList() { return (A) new ArrayList<>(); } Cannot infer arguments Incompatible types Runtime error I once wright code like this
  • 43. public class B { public static <T> T foo() { try { return (T) new Integer(42); } catch (ClassCastException e) { return (T) "ArtClub"; } } public static void main(String[] args) { System.out.println(B.<String>foo()); } } Compile error Runtime error print 42 print ArtClub ClassCastException
  • 44.
  • 46. List<Integer> integers = new ArrayList<Integer>(); List list = integers; List<Number> numbers = list; numbers.add(9.78d); 9.78 ClassCastException Compile Error 9 System.out.println(numbers.get(0)); System.out.println(integers.get(0));
  • 47.
  • 49. Set<Number> set = new TreeSet<>(); set.add(1); set.add(1L); set.add(1.00); System.out.println(set.size()); A. 3 B. Compile error C. 2 D. Runtime error
  • 51. public static void main(String[] args) { setFirst(new String[10], } 1.incompatible types 2.ClassCastException 3.cannot infer arguments 4.i don’t believe generics anymore //JDK 7 1); new Integer(1)); static <T> void setFirst(T[] ar, T s) { ar[0] = s; } // ну ок
  • 52. How we fix it? static <T, S extends T> void setFirst(T[] ar, S s) { ar[0] = s; } public static void main(String[] args) { setFirst(new String[10], new Integer(1)); } // compile error //JDK8 // ArrayStoreException
  • 54. abstract class DefaultList<T> { abstract void add(T ... elements); void addNotNull(T...elements) { for (T element : elements) { if (element != null); add(element); } } } public class ConcreateList extends DefaultList<String> { private final List<String> list = new ArrayList<>(); @Override void add(String... elements) { list.addAll(Arrays.asList(elements)); } @Override public String toString() { return list.toString(); } public static void main(String[] args) { DefaultList<String> stringList = new ConcreateList(); stringList.addNotNull("null", null); System.out.println(stringList); } } 1. «null» 2. «null», «null» 3. Compile error 4. Runtime error // error here // error here // error here
  • 55.
  • 57. public class Compressor<T> { String compress(Collection<?> obj) { String s = ""; for (Object o : obj) s += obj.toString(); return s; } int compress(List<Integer> list) { int result = 0; for (int i: list) result+=i; return result; } public static void main(String[] args) { List<String> list = Arrays.asList("1","2","3"); System.out.println(new Compressor().compress(list)); } } 1. Compile error 2. Runtime error 3. 6 4. 123 // classCastException
  • 58. PECS (Producer - extends, Consumer - super) If a parametrized type represents a T producer - use <? extends T>; If a parametrized type represents a T consumer - use <? super T>; Joshua Bloch public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp);
  • 59. Integer i = 127; Class<Integer> c = i.getClass(); //compile error Why this isn’t working?class Object { Class<?> getClass(); } class Number { Class<Number> getClass(); } class Integer { Class<Integer> getClass();
  • 60.
  • 61. 1, 2, 3, 1440988108 1, 2, 3, 23 nov 2016 19:56:00:00:00 ClassCastException Compile error List<Long> list = new ArrayList<>(); list.add(1L); list.add(2L); list.add(3L); Date now = new Date(); list.add(now); for (def node: list) { System.out.println(node); }
  • 62.
  • 63.