Generic Types,
Wrapper
Classes
IT Academy
Agenda
• Wrapper Pattern
• Generics Types
• Bounded Arguments
• Template Arguments
• Disadvantages of Generics
• Wrapper Classes
• Autoboxing and Unboxing
Wrapper Pattern
• Non-generic Box class:
public class Box {
private Object obj;
public void set(Object obj) { [Link] = obj; }
public Object get( ) { return obj; }
}
• Since its methods accept or return an Object, you are free to pass in
whatever you want, provided that it is not one of the primitive types.
• There is no way to verify, at compile time, how the class is used.
Wrapper Pattern
public class App {
public static void main(String[] args) {
String text = "Hello World";
Box box = new Box();
[Link](text);
Integer i = (Integer) [Link]();
}
Runtime
} Error
• One part of the code may place an Integer in the box and expect to get
Integers out of it, while another part of the code may mistakenly pass in
a String, resulting in a runtime error.
Generics Types
• Generics, introduced in Java SE 5.0
• A generic type is a generic class or interface that is parameterized
over types.
• Generics add a way to specify concrete types of general-purpose classes
and methods that operated on Object before.
• With Java's Generics features you can set the type for classes.
• Generic class is defined with the following format:
class Name<T1, T2, ..., Tn> { /* ... */ }
• The type parameter section, delimited by angle brackets (<>),
follows the class name.
Generics Types
• To update the Box class to use generics, you create a generic type
declaration by changing the code:
public class Box { }
to
public class Box<T> { }
• This introduces the type variable, T, that can be used anywhere inside
the class.
• To instantiate this class, use the new keyword, as usual, but place
<Integer> between the class name and the parenthesis:
Box<Integer> integerBox = new Box<Integer>();
[Link](42); // autoboxing
Generics Types
public class Box<T> {
// T stands for "Type".
private T value;
public void set(T value) { [Link] = value; }
public T get() { return value; }
}
• 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, or any array type.
• The same technique can be applied to create generic interfaces.
Generics Types
public class App {
public static void main(String[] args) {
String text = "Hello World";
Box<String> box = new Box<String>();
[Link](text);
Integer i = (Integer) [Link]();
Compile
}
} Error
• Generics also provide compile-time type safety that allows
programmers to catch invalid types at compile time.
Generics Methods
• Java method can be parametrized, too:
class ListUtil {
<T> T getRandomElement(List<T> list) { ... }
}
• As with class definitions, you often want to restrict the type parameter in
the method.
ListUtil listUtil = new ListUtil();
List<String> list = [Link]("One", "Two", "Three");
String value = listUtil.<String>getRandomElement(list);
Bounded Arguments
• Consider a simple drawing application to draw shapes (circles,
rectangles, …)
Shape Canvas
draw() draw(Shape)
drawAll(List<Shape>)
Limited to
Circle Rectangle List<Shape>
Bounded Arguments
• A List of any kind of Shape …
public <T extends Shape> void drawAll(List<T> shapes) { ... }
a Bounded
Template Arguments
• Shape is the upper bound of the wildcard.
Template Arguments
class Box<T extends Number> {
T[] nums; Integer inums[] = {1, 2 , 3 , 4, 5};
Double dnums[] = {1.0, 2.0, 3.0, 4.0, 5.0};
Box(T[] о) { nums = о; }
Box<Integer> iBox = new Box<Integer>(inums);
double average() { Box<Double> dBox = new Box<Double>(dnums);
double sum = 0.0;
for(int i=0; i < [Link]; i++) { if([Link](dBox))
sum += nums[i].doubleValue(); [Link]("Same");
} else
return sum/[Link]; [Link]("Not same");
}
boolean sameAvg(Box<T> obj) {
if(average() == [Link]()) Won’t compile!
return true;
return false;
}
}
Template Arguments
boolean sameAvg(Box<?> obj) {
if(average() == [Link]())
return true;
return false;
}
• The “collection of unknown” is a collection whose element type
matches anything – template arguments.
More fun with Generics
public void pushAll(Collection<? extends E> collection) {
for (E element : collection) {
[Link](element); All elements must be
}
at least an E
}
public List<E> sort(Comparator<? super E> comp) {
List<E> list = [Link]();
[Link](list, comp); The comparison method
return list;
}
must require at most an E
Disadvantages of Generics
• Generic-fields can’t be static.
• Can’t be made an explicit call to the constructor generic type:
class Optional<T> {
T value = new T();
} Won’t compile!
• The compiler does not know what constructor can be caused and the
amount of memory to be allocated when an object.
Wrapper Classes
• The wrapper classes are objects encapsulating primitive Java
types.
• Each Java primitive has a corresponding wrapper:
Autoboxing and Unboxing
• After Java 5 the conversion primitive value to an wrapper object
and from a wrapper object to a primitive value can be done
automatically by using features called autoboxing :
List<Integer> list = new ArrayList<>();
[Link](1); // autoboxing
Integer val = 2; // autoboxing
and unboxing :
Integer object = new Integer(1);
int val1 = getSquareValue(object); //unboxing
int val2 = object; //unboxing
public static int getSquareValue(int i) {
return i*i;
}
Thanks for
attention!
IT Academy