Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Java generics

No description
by

Georgian Parvu

on 3 December 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Java generics

Generic Type
JAVA

GENERICS

Generic Methods
Type Inference
Bounded Type Parameter
Restrictions
Wildcards
Type erasure
Polymorphysm
Provide Compile time safety
Purpose
List list = new ArrayList();
list.add("hello");
list.add(20);

for(Iterator it = list.iterator(); it.hasNext()){
System.out.println( (String) it.next() );
}
ClassCastException for you my friend.
int is not a String. Understood?
Back in the days
List<Candy> stringList = new ArrayList<Candy>();
stringList.add(new Lollipop());
stringList.add(new Spider());

for(String str : stringList){
System.out.println(str );
}
Spider ain't no candy man !?
I'm giving you a compile error.
Nowadays
Classes with Type Parameters
public class Box<T> {
private T t;
}

Box<Lego> legoBox = new Box<Lego>
Bag<Box<Lego>> legoBox = new Bag<Box<Lego>>

Box rawBox = new Box();
Type Parameter
Parameterized type
Raw types for
backwards
compability
Names
K- Key
N - Number
T - Type
V - value
E - Element
S,U,V etc. - 2nd, 3rd, 4th types
Methods with Type Parameters

public class Pair<K, V> {
private K key;
private V value;

public Pair(K key, V value) {
this.key = key;
this.value = value;
}

public void setKey(K key) { this.key = key; }
public void setValue(V value) { this.value = value; }
public K getKey() { return key; }
public V getValue() { return value; }
}

public class Util {
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());
}
}

Pair<Integer, String> p1 = new Pair<Integer, String>(1, "apple");
Pair<Integer, String> p2 = new Pair<Integer, String>(2, "pear");
boolean same = Util.<Integer, String>compare(p1, p2);
Need to add type parameter before method's return type
Pair<Integer, String> p1 = new Pair<Integer, String>(1, "apple");
Pair<Integer, String> p2 = new Pair<Integer, String>(2, "pear");
boolean same = Util.<Integer, String>compare(p1, p2);
Determines the needed type parameters since Java 7
Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.compare(p1, p2);
Easier calls
Easier calls
Autoboxing
Diamonds
In this context, extends is used either "extends" (as in classes) or "implements" (as in interfaces) thus, objects must pass the 'IS-A' test
Why ?
How ?
To be more specific with the types accepted
Use extends keyword, followed by its upper bound(s).
Extends ?
Coding language please !
public class NaturalNumber<T extends Integer> {
private T n;

public NaturalNumber(T n) { this.n = n; }
public boolean isEven() {
return n.intValue() % 2 == 0;
}
}
class Duster<T extends S & U & V>

Class S
Interface U
Interface V
Single bound
Multiple bounds
great for algorithms
public static <T> int countGreaterThan(T[] anArray, T elem) {
int count = 0;

for (T e : anArray)
if (e > elem)
++count;
return count;
}
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;

for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
Applies only to primitives
Without bounded type parameters
With bounded type parameters
Provide more flexibility to the type of a parameter, field, or local variable by introducing the '?' type representing the unknown type and
Upper bounded wildcards
Lower bounded wildcards
Unbounded wildcards
public static void printList(List<?> list) {
for (Object elem : list)
System.out.println(elem + " ");
System.out.println();
}
List<Integer> li = Arrays.asList(1, 2, 3);
List<String> ls = Arrays.asList("one", "two", "three");
printList(li);
printList(ls);
Almost like bounded type only use '?' instead of 'T'
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));
Another difference ?
public void addRectangle(List<? extends Shape> shapes) { shapes.add(0, new Rectangle());}
Yes, used for read-only methods.
Compile time error since we can add either Circle, Rectangle or Shape. Breaking what generics stand for.
In this context, super restricts the unknown type to be a specific type or a super type of that type.
Why ?
How ?
Antonym for upper bounded wildcards
Use ? followed by super keyword, followed by its lower bound.
Super ?
public static void addNumbers(List<? super Integer> list) {
for (int i = 1; i <= 10; i++) {
list.add(i); }
}
Will allways be at least an Integer
So what?
Lower bounds are used for write-only methods. Yeah, write only, since a super class may not have the new methods added by it's subtype
Box<Number> box = new Box<Number>();
box.add(new Integer(10));
box.add(new Double(10.1));
public void boxTest(Box<Number> n) { /* ... */ }
boxTest(new Box<Integer>);
Generic types and methods
List<? extends Integer> intList = new ArrayList<>();
List<? extends Number> numList = intList;
Wildcards
Adds
Why ?
How ?
Old code using Collections must run with the new generic Collections. This is called 'Migration compability'. That's why we have raw types.
Erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.
Code translation ?
public class Node<T> {
private T data;
private Node<T> next;

public Node(T data, Node<T> next) }
this.data = data;
this.next = next;
}

public T getData() { return data; }
}
public class Node {
private Object data;
private Node next;

public Node(Object data, Node next) {
this.data = data;
this.next = next;
}

public Object getData() { return data; }
}
Compile time
Run time
public class Node<T extends Comparable<T>> {
private T data;
private Node<T> next;

public Node(T data, Node<T> next) }
this.data = data;
this.next = next;
}

public T getData() { return data; }
}
public class Node {
private Comparable data;
private Node next;

public Node(Comparable data, Node next) {
this.data = data;
this.next = next;
}

public Comparable getData() { return data; }
}
How ?
No primitives allowed, since they are not objects
Cannot create instances of type parameters
public static <E> void append(List<E> list) {
E elem = new E();
list.add(elem);
}
Compile Time Error
Cannot declare static fields whose
types are type parameters
Cannot use casts or instanceof
with parameterized types
public static <E> void rtti(List<E> list) {
if (list instanceof ArrayList<Integer>) {}
}
Compile Time Error
Cannot overload a method where
the formal parameter types of each
overload erase to the same raw type
public class Example {
public void print(Set<String> strSet) { }
public void print(Set<Integer> intSet) { }
}
Cannot create, catch, or throw objects of parameterized types
class MathException<T> extends Exception
public static <T extends Exception, J> void execute(List<J> jobs) {
try {/*..*/
} catch (T e) {
}
}
Georgian Parvu
Q & A
Full transcript