Showing posts with label Generics. Show all posts
Showing posts with label Generics. Show all posts

Friday, 1 July 2011

Wildcards in Java Generics

What is covariance, contravariance and invariance?
As we've seen in the previous post, the subtyping relation of generic types is invariant. Sometimes, though, we'd like to use generic types in the same way we can use ordinary types:

  • Narrowing a reference (covariance).
  • Widening a reference (contravariance
Wildcard in Generics

Lower - bounded wildcards in Generics
Upper bounded wildcards in Generics
Using multiple bounds in Generics
The get and put principle of bounded wildcard
Restriction of Wildcards in generics

Subtyping in Generics

Before starting on subtyping in Generics, let's first understand what is covariance.
See - What is covariance, contravariance and invariance?

In Java, as in other object-oriented typed languages, hierarchies of types can be built:
 
In Java, a subtype of a type T is either a type that extends T or a type that implements T (if T is an interface) directly or indirectly. Since "being subtype of" is a transitive relation, if a type A is a subtype of B and B is a subtype of C, then A will be a subtype of C too. In the figure above:
  • FujiApple is a subtype of Apple.
  • Apple is a subtype of Fruit.
  • FujiApple is a subtype of Fruit.
Every Java type will also be subtype of Object.

Every subtype A of a type B may be assigned to a reference of type B:

Apple a = ...;
Fruit f = a;


Subtyping of Generic Types - Parametrized Type Invariance

If a reference of an Apple instance can be assigned to a reference of a Fruit, as seen above, then what's the relation between, let's say, a List<Apple> and a List<Fruit>? Which one is a subtype of which? More generally, if a type A is a subtype of a type B, how does C<A> and C<B> relate themselves?

Surprisingly, the answer is: in no way. In more formal words, the subtyping relation between generic types is invariant.
Eg.
List<Apple> apples = new ArrayList<>();
List<Apple> foulApples = apples; //fine 
Collection<Apple> greenApples = apples; //fine again


However this is not fine:
List<Apple> apples = new ArrayList<>();
List<Fruit> fruits = apples;//Error

and so does the following:

List<Apple> apples;
List<Fruit> fruits = ...;
apples = fruits;

But why? Is an apple is a fruit, a box of apples (a list) is also a box of fruits.

In some sense, it is, but types (classes) encapsulate state and operations. What would happen if a box of apples was a box of fruits?

List<Apple> apples = ...;
List<Fruit> fruits = apples;
fruits.add(new Strawberry());

If it was, we could add other different subtypes of Fruit into the list and this must be forbidden.

The other way round is more intuitive: a box of fruits is not a box of apples, since it may be a box (List) of other kinds (subtypes) of fruits (Fruit), such as Strawberry.


So what if they were covariant?

Please go through the comments to see what is the problem:
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(122));
List<Object> lo = li; // Problem starts here
Object num = lo.get(0); // Nothing wrong with this
lo.add("Bang!"); // This would be OK through
// lo but what about li
Integer i = li.get(1); // ClassCastException


Parametrized types and Arrays : Covariance of Arrays

Array types are covariant,  if a type A is a subtype of type B, then A[] is a subtype of B[].

However we have just seen that the parameterised types are not covariant. This leads to an anomaly that cannot be resolved, so Java has the rule that arrays of parameterised types are not allowed. Otherwise we could write code that would potentially cause a ClassCastException, and the whole idea behind the generic types is to remove this possibility so long as no compiler warnings are issued.

Places where covariance of arrays may be harmful:
Case 1 : ArrayStoreException
Apple[] apples = new Apple[1];
Fruit[] fruits = apples;
fruits[0] = new Strawberry();//generates ArrayStoreException

The code indeed compiles, but the error will be raised at runtime as an ArrayStoreException. Because of this behavior of arrays, during a store operation, the Java runtime needs to check that the types are compatible. The check, obviously, also adds a performance penalty that you should be aware of.


Case 2: ClassCastException
List<String>[] wordlists = new ArrayList<String>[10];
ArrayList<Integer> ali = new ArrayList<Integer>();
ali.add( new Integer(123) );
Object[] objs = wordlists;
objs[0] = ali; // No ArrayStoreException
String s = wordlists[0].get(0); // ClassCastException

Once more, generics are safer to use and "correct" this type safety weakness of Java arrays.

In the case you're now wondering why the subtyping relation for arrays is covariant, I'll give you the answer that Java Generics and Collections give: if it was invariant, there would be no way of passing a reference to an array of objects of an unknown type (without copying every time to an Object[]) to a method such as:

void sort(Object[] o);

With the advent of generics, this characteristics of arrays is no longer necessary (as we'll see in the next part of this post) and should indeed by avoided.

Advantage of Generics

Pretty much the same way, methods and constructors can be generic if they declare one or more type variables.

public static <T> T getFirst(List<T> list)

This method will accept a reference to a List<T> and will return an object of type T.


Examples

You can take advantage of generics in both your own classes or the generic Java library classes.

Type Safety When Writing...

In the following code snippet, for example, we create an instance List<String> of populate it with some data:

List<String> str = new ArrayList<String>();
str.add("Hello ");
str.add("World.");

If we tried to put some other kind of object into the List<String>, the compiler would raise an error:

str.add(1); // won't compile

... and When Reading

If we pass the List<String> reference around, we're always guaranteed to retrieve a String object from it:

String myString = str.get(0);

Iterating

Many classes in the library, such as Iterator<T>, have been enhanced and made generic. The iterator() method of the interface List<T> now returns an Iterator<T> that can be readily used without casting the objects it returns via its T next() method.


for (Iterator<String> iter = str.iterator(); iter.hasNext();) {
  String s = iter.next();
  System.out.print(s);
}

Using foreach

The for each syntax takes advantage of generics, too. The previous code snippet could be written as:

for (String s: str) {
  System.out.print(s);
}

that is even easier to read and maintain.

Autoboxing and Autounboxing

The autoboxing/autounboxing features of the Java language are automatically used when dealing with generics, as shown in this code snippet:

List<Integer> ints = new ArrayList<Integer>();
ints.add(0);
ints.add(1);
      
int sum = 0;
for (int i : ints) {
  sum += i;
}

The Generics Facility

The generics facility introduced the concept of type variable. A type variable, according to the Java Language Specification, is an unqualified identifier introduced by:


Writing Generic interface

A class or an interface is generic if it has one or more type variable. Type variable are delimited by angle brackets and follow the class (or the interface) name:

public interface List<T> extends Collection<T> {
  ...
}

Roughly speaking, type variables act as parameters and provide the information the compiler needs to make its checks.

Many classes in the Java library, such as the entire Collections Framework, were modified to be generic. The List interface we've used in the first code snippet, for example, is now a generic class. In that snippet, box was a reference to a List<Apple> object, an instance of a class implementing the List interface with one type variable: Apple. The type variable is the parameter that the compiler uses when automatically casting the result of the get method to an Apple reference.

In fact, the new generic signature or the get method of the interface List is:

T get(int index);

The method get returns indeed an object of type T, where T is the type variable specified in the List<T> declaration.

Friday, 24 June 2011

Converting a Collection to an array

If you have been using Collections in Java 5 you probably have stumbled upon a problem of converting a given Collection<T> into an array of type T. In the Collection interface, there is a method called toArray() which returns an array of type Object[]. But then, if since Java 5 Collections are using generics, shouldn’t it be possible to get an array T[] of the generic type we used in the declaration of our Collection<T>? Well, there is a method T[] toArray(T[] a). But what is that strange “T[] a” doing there? Why is there no simple method T[] toArray() without any strange parameters? It seams like it shouldn’t be a big problem to implement such a method… but actually it is not possible to do so in Java 5, and we will show here why.
Let’s start from trying to implement that method by ourselves. As an example, we will extend the ArrayList class and implement there a method T[] toArrayT(). The method simply uses the standard Object[] toArray() method and casts the result to T[].

import java.util.*;

/**
 * Implementation of the List interface with "T[] toArrayT()" method.
 * In a normal situation you should never extend ArrayList like this !
 * We are doing it here only for the sake of simplicity.
 * @param <T> Type of stored data
 */
class HasToArrayT<T> extends ArrayList<T> {
public T[] toArrayT() {
return (T[]) toArray();
}
}

public class Main {
public static void main(String[] args) {
// We create an instance of our class and add an Integer
HasToArrayT<Integer> list = new HasToArrayT<Integer>();
list.add(new Integer(4));

// We have no problems using the Object[] toArray method
Object[] array = list.toArray();
System.out.println(array[0]);

// Here we try to use our new method... but fail on runtime
Integer[] arrayT = list.toArrayT(); // Exception is thrown :
// "Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer"
System.out.println(arrayT[0]);
}
}

If you compile it and run, it will throw an exception when trying to use our new method. But why? Didn’t we do everything right? Objects stored in the array ARE Integers and toArray method returns an array of those objects, so what is the problem?

Java compiler gives us a hint to understand what is wrong. During compilation, you should see a warning at line 12, saying something like “Type safety: Unchecked cast from Object[] to T[]“. Let’s follow this trace and check if the array that comes out of our toArrayT method is really of type Integer[]. Put this code somewhere in main() method before the Integer[] arrayT = list.toArrayT() line :

System.out.println("toArrayT() returns Integer[] : "
+ (list.toArrayT() instanceof Integer[]));

When you run the program, you should get “false”, which means that toArrayT() DID NOT return Integer[]. Why? Well, many of you probably know the answer – it is Type Erasure. Basically, during compilation the compiler removes every information about the generic types. Effectively, when the program runs, all the appearances of T in our HasToArrayT class are nothing more than simple Object’s. It means, that the cast in the function toArrayT does not cast to Integer[] any more, even if we are using Integer in the declaration of the generic type. Actually, there is also a second problem here, coming from the way Java handles casting of arrays. This time however we would like to concentrate just on the first one – usage of generics.
So, if the information that T is an Integer is no longer there at runtime, is there any way to really return an array of type Integer[] ? Yes, there is, and it is exactly what the method T[] toArray(T[] a) in the Collections framework is doing. But the price you have to pay for it is the additional argument a, whose instance you have to create first by yourself. How do they use it there? Let’s look at how it is really implemented in, for example, ArrayList :

public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}

As it is explained in the method’s Javadoc, if the specified array a is big enough it just copies elements into this array. If not, it creates a new array. What is important for us, is that when creating a new array it uses Arrays.copyOf method, specifying there a.getClass() as the type of array to create. So that’s where it needs that additional argument – to know what type of array to create. But then you might say, would it not be easier to fit there T.class instead of a.getClass()? No. Because of type erasure, T is no longer the type we specified. Moreover, we would get a compile time error if we wrote T.class! Some of you may be thinking about creating a new array the simple way – new T[], but it is also not possible because of the same reason. We have already discussed how to get Generic Arrays in Java here.
To put it straight, in order to return a new array of T, the type that we really specified, we MUST give something of that type to the function toArray. There is no other way the function could now what type of array it should create, because the generic type T supplied when creating that Collection is erased every time during compilation.
One other way to implement such a method is by using the Class<T[]> type as an input parameter. This way, instead of having to create a new instance a of array T[] and then using it in the function toArray(a), we could use the .class field – toArrayT(TYPE[].class) :

public T[] toArrayT(Class<T[]> c) {
return (T[]) Arrays.copyOf(toArray(), size(), c);
}

It still takes an argument, but it has two advantages over the T[] toArray(T[] a) function. First, it does not require you to create an instance of an array just to pass it to the function. Second, it is simpler. Of course, it has still the disadvantage of having to pass some argument.

After all, there is no perfect way to perform such a conversion. The best solution would be not to use arrays at all. Code with arrays is difficult to maintain and invites people to make mistakes that often come out not earlier than on runtime. Using collections is generally much preferred and if you use them all the time, you will not be forced to deal with the toArray method.

Thursday, 23 June 2011

Type Safety: why would you need a Collections.checkedSet in JDK1.4?

In one of the first posts on this blog I have discussed the problem of type checking (or lack of it) in some of Java collections even when using generics. Today I want to show you a similar issue that can break the type safety in your code. It’s a problem that can cause a really nasty bugs in your application – the ones that manifest themselves many thousand lines of code after the faulty method introduce it.
Imagine that you work with generics, but you use a third party code. What if some part of that code was written in Java 1.4 or earlier, therefore not using generics. Let’s go one step further: what if (for some reason) this code does not respect the typing of your collections? You would expect to get an error, right? Well, you’ll get one… but do you know when? Check the following code:

public static void main(String[] args) {
// create a type-safe set of Integers and add some values to it
Set<Integer> setOfInts = new HashSet<Integer>();
setOfInts.add(new Integer(7));
setOfInts.add(new Integer(13));

// pass your set to a non-generic code
Set uncheckedSet = setOfInts;
// non-generic code does not respect your typing
// and adds a String to your set of integers
uncheckedSet.add(new String("Illegal"));

// back in your code - do some set manipulations:
System.out.println(setOfInts);
setOfInts.remove(new Integer(7));

// at the end iterate trough your set
for (Integer integer : setOfInts) {
System.out.println(integer);
}
}

The code above is a simplified version of the described scenario. In lines 8 – 11 the ‘third party’ code is executed and adds a String into a set of Integers. So back to the question: in a given example when will error occur? One might assume in line 11 as the bad element is inserted… wrong! Maybe when we access the collection and print all of its elements?… wrong! We can even do some manipulations on it (line 15) and still be fine! The error will show his ugly head finally in the loop in line 18 when we will enter it for the second time. This will happen so late because in line 18 for the first time we access the inserted String and cast it to Integer – at this point ClassCastException occurs.
In the example above the distance between the faulty insertion and the place where exception is thrown is only seven lines, but you can imagine its being 7000. Your code can be working fine for 7000 hours and after that throw an exception that will basically give you no hint what’s wrong. If you do not use third party code you should not feel safe because of that – I am sure that if your project has more than 10000 lines there is a part of it so old and dusty that it was written without the usage of generics…
What can be done? Well, we are in luck as there is a quite simple way of protecting yourself from that: in java.util.Collections you will find a way to wrap your Set, Map or List into an forwarding class that will check in runtime the typing of the inserted objects. In the case of our code snippet we only need to add one line:

public static void main(String[] args) {
// create a type-safe set of Integers and add some values to it
Set<Integer> setOfInts = new HashSe<Integer>();
setOfInts = Collections.checkedSet(setOfInts, Integer.class);
setOfInts.add(new Integer(7));
setOfInts.add(new Integer(13));

// pass your set to a non-generic code
Set uncheckedSet = setOfInts;
// non-generic code does not respect your typing
// and adds a String to your set of integers
uncheckedSet.add(new String("Illegal"));

// back in your code - do some set manipulations:
System.out.println(setOfInts);
setOfInts.remove(new Integer(7));

// at the end iterate trough your set
for (Integer integer : setOfInts) {
System.out.println(integer);
}
}

As you see the only difference between this and previous snippet is additional line (#4) in which we wrap our set of integers into a CheckedSet. See that due to Generic type erasure in Java the Collections.checked* methods require a class object besides a collection to wrap. Now when we run the new code the error will manifest itself just at the moment where an error is commited: in line 12 when we try to insert a string. Exactly what we needed!

To summarize: if in your project you use either third party code or legacy code that you suspect of not using generics consider wrapping your collections with Collection.checked* methods!


Note :
Users with jdk 6 or higher will get ClassCastException in any case, if they add some wrong datatype.

Type safety in Java Set and Map in JDK 1.4

Probably many of you still remember the lack of type checking in Java 1.4 Collections and how much hassle it was to deal with casting the collection elements, not to mention how many errors this introduced to the code. Since introduction of generics in Java 1.5 this have really improved and one might think that nowadays the language itself protects the programmer from the silliest of typing mistakes. Generics themselves brought with them a set of new complications, but it seems reasonable to think that in the basic code situations when using Java’s Sets or Maps and when there is no kung-fu complications like wildcards or casting we are safe and secure. Are we really?
Recently I have encountered a bug in a production code when dealing with a simple (really simple) usage of a Map. The embarassing part of this issue was that it took lots of effort to debug it and the cause of it was… well… trivial. The code below shows a sketch of how the code looked like before the bug was introduced. In real life the class was a part of a really old and rarely edited legacy code, obviously it was much larger than the one below:

import java.util.HashMap;
import java.util.Map;

public class EmployeeDataLookup {
// A map storing relation between employee ID and name.
private Map<Integer, String> employeeIdToName;

public EmployeeDataLookup() {
// Create a new EmployeeDataLookup and initialize
// it with employee names and IDs.
employeeIdToName = new HashMap<Integer, String>();
addEmployee(301, "John Doe");
addEmployee(302, "Mary Poppins");
addEmployee(303, "Andy Stevens");
}

public void addEmployee(int employeeId, String employeeName) {
employeeIdToName.put(employeeId, employeeName);
}

// This class is very complicated and has many other methods...

// Lookup method for finding employee name for given employee ID.
public String findEmployeeName(int employeeId) {
return employeeIdToName.get(employeeId);
}

public static void main(String[] args) {
// Create a EmployeeDataLookup instance
EmployeeDataLookup employeeLookup = new EmployeeDataLookup();
// Find the name of an employee with ID = 301
String employeeName = employeeLookup.findEmployeeName(301);
System.out.print("Employee 301 : " + employeeName);
}
}

So what went wrong? Well, at some point the project functionality requirements have changed (surprising, right?) and the key of the map storing data inside of the class had to be changed. In terms of the example above you might say that a company has merged with one of the vendors, so the system storing the employee data had to be made compatible with the ID system of the vendor. Because the vendor company used 13 digit IDs to identify its employees the change to the code in Java terms meant that instead of using Integers we had to change to Longs. Simple right? Its even easier if you use an IDE like Eclipse – just change/refactor the Map key type in line 7 from Integer to Long, let the editor show you all the errors, fix them and that is it! In five minutes all is done:

import java.util.HashMap;
import java.util.Map;

public class EmployeeDataLookup2 {
// A map storing relation between employee ID and name.
private Map<Long, String> employeeIdToName;

public EmployeeDataLookup2() {
// Create a new EmployeeDataLookup and initialize
// it with employee names and IDs.
employeeIdToName = new HashMap<Long, String>();
addEmployee(301, "John Doe");
addEmployee(302, "Mary Poppins");
addEmployee(303, "Andy Stevens");
}

public void addEmployee(long employeeId, String employeeName) {
employeeIdToName.put(employeeId, employeeName);
}

// This class is very complicated and has many other methods...

// Lookup method for finding employee name for given employee ID.
public String findEmployeeName(int employeeId) {
return employeeIdToName.get(employeeId);
}

public static void main(String[] args) {
// Create a EmployeeDataLookup instance
EmployeeDataLookup employeeLookup = new EmployeeDataLookup();
// Find the name of an employee with ID = 301
String employeeName = employeeLookup.findEmployeeName(301);
System.out.print("Employee 301 : " + employeeName);
}
}

The change above introduced the bug. Can you see it? When you run the main method now you will find out that the name of the employee with ID=301 is ‘null’! Ha!

If you do not see the trouble (or are to lazy to try) I’ll give you a hint: check out the function findEmployeeName . If you have seen it, try to imagine that this class in real life had 1000+ lines of code unrelated to the changed map. Since there are no compile errors it was like looking for a needle in a haystack… so what’s the bug exactly?

The problem is that after introducing generics, probably due to backward compatibility, some of the methods in Collection and Map interface have not been changed and still do not perform type checking. One of them is Map.get(Object) which have caused the bug in the code above. After the ’simple change’ we have still been using Integer keys to access the map that contained Longs, so even though we had a record of employee 301 in our system the get method returned null. And because of the lack of type checking there were no warnings… Busted.

So what’s the lesson from this? Be cautious about type checking even in the most basic situations. Remember that access methods in Sets, Lists and Maps can behave and bite you in the behind. The biggest pain is that the bugs introduced this way are usually hard to spot by a human, so sometimes a dozen of engineers staring at the code can have trouble finding it. There is a way to deal with them though – most of them can be easily found if you are using a static code analysis tool (eg: FindBugs).

Note:
If you are using JDK 6 or higher, its no worries for you. Because in any case you would get the correct result.

Tuesday, 14 June 2011

How to create and initialize generic array in java ?

I recently required generic array in my project. But in java, to initialize array generically is a problem, because the way generics are implemented.

So for eg. you can't do this :
public class GenericArray<E> {
private E a[];
public GenericArray()
{
a = new E[INITIAL_ARRAY_LENGTH];
}
}

Solution 
But still I googled and found some solutions.
Solution 1 : Use reflections
So one solution to this using reflection, and making an array at runtime and point the reference to some new array.
class GenericArray<T> {
public GenericArray(Class<T> clazz,int capacity) { 
//Create array at runtime using reflections 
array=(T[])Array.newInstance(clazz,INITIAL_ARRAY_LENGTH);
}

private final T[] array;
}

Solution 2 : Use Object[] and cast to E
2nd solution is to use Object Class to solve the problem :

E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];

Or if you need value to be returned from the array at particular index try this :

public class GenericArray<E>{
private Object[] a;


public GenSet(int s) {
a = new Object[s];
}


@SuppressWarnings({"unchecked"})
E get(int i) {
return (E) a[i];
}
}

This solved what I needed, but not in a clean way. But if thing works, it good for us. :)


Thursday, 19 May 2011

Generic Lists in java

By default you can put any Object into a List, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a List. Here is an example:

List<MyClass> list = new ArrayList<MyClass>();


This List can now only have MyObject instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:

MyClass myObject = list.get(0);

for(MyClass anObject : list){
//do someting to anObject...
}



However, note that this support for custom classes and generics is compile time only. Because if you try to add object of AnyOtherClass to MyClass, it will throw compile time error. At runtime, JVM doesn't make any difference between List of Strings or List of Integer or List of MyClass.

Tuesday, 19 April 2011

Bounding the Parameterized Types

Generics won't be complete if this section is not covered. It is all about bounding parametric types. Till now, we have seen parametric types operate on a single java type like Object or String. Now, let us see how the parametric types can be restricted by applying some constraints over them. For this to be illustrated, let us take a sample application called Animal Actions.
Animal Actions class performs various operations on a given Animal like: making them eat, sleep and run. The first constraint that we see here is that only an Animal object can be passed to the Animal Actions class. Let us represent the Animal class as follows.
Animal.java
package generics.bounds;

public abstract class Animal
{
// Some common functionalities here.
}
Note that the Animal class is declared as abstract, meaning that some other concrete class is going to extend this Animal class. Another restriction that we see in Animal Actions class is that they will make the Animals to sleep, eat and run. Since these are behaviors and we may give different representations for the same, let them be modeled as interfaces. Following code shows the interface design for the behaviors,

package generics.bounds;

interface Sleepable
{
public void sleep();
}

interface Runnable
{
public void run();
}

interface Eatable
{
public void eat();
}
Let us give implementation of the above behaviors for some animal, say Dog. The following code snippet is for the implementation of Dog which conforms to eating, sleeping and running behavior.
Dog.java
package generics.bounds;

public class Dog extends Animal implements Sleepable, Runnable, Eatable
{
public void sleep()
{
System.out.println("Dog is sleeping");
}

public void run()
{
System.out.println("Dog is running");
}

public void eat()
{
System.out.println("Dog is eating");
}
}
Now, let us design the Animal Actions class. The restriction we have on Animal Actions class is that, we should operation on any type of object that is an Animal which can eat, sleep and run. Look into the following Animal Actions class,
AnimalActions.java
package generics.bounds;

public class AnimalActions<A extends Animal & Sleepable & Runnable & Eatable>
{
private A animal;

public AnimalActions(A animal)
{
this.animal = animal;
}

public A getAnimal()
{
return animal;
}

public void setAnimal(A animal)
{
this.animal = animal;
}

public void doActions()
{
animal.sleep();
animal.run();
animal.eat();
}
}
The declaration of the parameterized class looks like the following,

public class AnimalActions<A extends Animal & Sleepable & Runnable & Eatable
Let us break down the pieces in the above declaration. The first trivial stuff that has to be noted is the declaration of the typed parameter A (which is for Animal). The next set of expressions are imposing restrictions on the typed parameter A. The phrase 'A extends Animal' tells that whatever type we pass for the substitution parameter must extend/implement the Animal class/interface. The type that comes after extends can either be an interface or a class. It is illegal to mention something like the following,

public class AnimalActions<A implements SomeInterface>
Only extends keyword is used for both class as well the interface and not the implements keyword. If we want the parametric type to confirm by more than one classes or interfaces, then every types should be separated by the symbol &. For example, in our case, we want some Animal to eat, sleep and run by implementing the Eatable, Sleepable and Runnable interface. So, we have declared something like AnimalActions<A extends Animal & Sleepable & Runnable & Eatable. To sum up things, the generic class declaration can be interpreted like this; it can be passed with any type that implements/extends Animal, Sleepable, Runnable and Eatable types.
Following code snippet makes use of the above Animal Actions class. In the below code, a new instance of Dog object is created and passed on to the constructor of the Animal Actions class. This is perfectly valid as the Dog class extends the Animal class and it also implements Sleepable, Eatable and Runnable interfaces. It then makes a call to AnimalActions.doActions(), thereby the execution gets directed towards Dog.sleep(), Dog.eat() and Dot.run().
AnimalActionsTest.java
package generics.bounds;

public class AnimalActionsTest
{
public static void main(String[] args)
{
AnimalActions<Dog> animal = new AnimalActions<Dog>(new Dog());
animal.doActions();
}
}

Generics : Index or TOC

Generics in java 

Motivation behind Generics-Dealing with casting of objects
The Generics Facility  
Creating a Generic class
Writing a Generic Method

Naming convention in generics
Generics are syntactic sugar - Type Erasure with Generics
Advantage of Generics



Subtyping a generic type

Wildcards in Generics
Generics classes in java vs templates in c++


Some mistakes to be avoided with generics:
Beginner's mistake of using Object as type parameter to make method generic
Generic methods: How generic are generic method?
Wildcards in Generics 
Bounded parametric types 
Covariance, contravariance, invariance
Upper bound boundedness in generics
Lower bound boundedness in generics
Multiple bounds in generics
Get and Set principle in generics
Restrictions on wildcards in generics
Expressing dependencies in type parameters : Wildcards vs type parameters

Class objects as type literals
Generic types are not covariant
Type erasure in generics
Making return type of method as generic
Covariant parameter types

The Get and Put Principle in bounded wildcard (Generics)

Use extends only when you intend to get values out of a structure or Collection, use super only when you intend to put values into a structure or Collection.
This also implies: don’t use any wildcards when you intend to both get and put values into and out of a structure.

// Copy all elements, subclasses of T, from source to dest 
//which contains elements that are superclasses of T.public static <T> void copy(List<? super T> dest, List<? extends T> source) {
for (int i = 0; i < source.size(); i++) {
dest.set(i, source.get(i));
}
}

// Extends wildcard violationList<Integer> integers = new LinkedList<Integer>();
List<? extends Number> numbers = integers;
numbers.get(i); // Works fine!numbers.add(3); // Won't compile!
// Super wildcard violationList<Number> numbers = new LinkedList<Number>();
List<? super Integer> integers = numbers;
numbers.add(3); // Works fine!int i = numbers.get(0); // Won't' compile!Object o = numbers.get(0); // Works fine since object is the upper bound!

Restrictions on wildcards in generics:

The get and put principle is one of the restrictions on wildcards. Additional to the above principle there are also a few restrictions on wildcards: Don’t use wilcards when creating instances, specifying generic method calls and extending superclasses:
List<?> integers = new LinkedList<?>();         // Won't compile!List<?> integers = Lists.<?>factory();          // Won't compile!class AnyList implements List<?> {}             // Won't compile!

Using multiple bounds in generics

The <A extends B> syntax applies even if B is an interface because 1) it doesn't matter operationally if B is a class or an interface and 2) if B is a type parameter, the compiler doesn't know a priori whether it is a class or an interface.  
Since Java allows multiple inheritance in the form of implementing multiple interfaces, it is possible that multiple bounds are necessary to specify a type parameter.    To express this situation, one uses the following syntax:
<T extends A & B & C & ...>
For instance:
  interface A {
...
}

interface B {
...
}

class MultiBounds<T extends A & B> {
...
}

Lower Bounded Wildcards in Generics

Suppose we wish to write a method called copyTo()such that it copies the data the opposite direction, i.e. from the host object to the given object:
public void copyTo(Box<E> b) {
  b.data = this.data(); 
}

The above code works fine so long as you are copying from one Box to another of exactly the same type (invariant type relationship), e.g. both are Box<Integer> or both are Box<String>. 

But operationally, b could be a Box of any type that is a superclass of E and the copying would be type safe.  This is a contravariant type relationship between Box<E> amd the input parameter to the copyTo() method where the type parameter of the object referenced by the variable b  is a superclass of E.
To express this, we write
public void copyTo(Box<? super E> b) {
  b.data = this.data();  // b.data is a superclass of this.data
}

The type parameterization <? super E> is called a "lower bounded wildcard" because it defines a type that could be any type so long as it is bounded by the subclass E.
Once again, we have greatly increased the utility of the copyTo() method because it is now not limited to only inputs of type Box<E> but will now work with any compatible Box object.
Upper and lower bounded wildcards will prove indispensable when implementing the visitor pattern on generic (parameterized) classes.

Expressing dependencies in type parameters : Wildcards vs bounded type parameters

This article explains When should I use generic methods, and when should I use wildcard types?
To understand the answer, let’s examine a few methods from the Collection libraries. It has to methods :
containAll and addAll .

Using wildcard:

interface Collection<E> {
public boolean containsAll(Collection<?> c);
public boolean addAll(Collection<? extends E> c);
}

Using Bounded type parameters
We could have used generic methods here instead:
interface Collection<E> {
public <T> boolean containsAll(Collection<T> c);
public <T extends E> boolean addAll(Collection<T> c);
// hey, type variables can have bounds too!
}

However, in both containsAll and addAll, the type parameter T is used only once.
The return type doesn’t depend on the type parameter, nor does any other argument to the method (in this case, there simply is only one argument).

This tells us that the type argument is being used for polymorphism; its only effect is to allow a variety of actual argument types to be used at different invocation sites. If that is the case, one should use wildcards. Wildcards are designed to support flexible subtyping, which is what we’re trying to express here.

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn’t such a dependency, a generic method should not be used.


It is possible to use both generic methods and wildcards in tandem. Here is the method Collections.copy():

class Collections {
    public static <T> void copy(List<T> dest, List<? extends T> src){...}
}

Note the dependency between the types of the two parameters. Any object copied from the source list, src, must be assignable to the element type T of the destination list, dst. So the element type of src can be any subtype of T - we don’t care which. The signature of copy expresses the dependency using a type parameter, but uses a wildcard for the element type of the second parameter.

We could have written the signature for this method another way, without using wildcards at all:
class Collections {
     public static <T, S extends T>
     void copy(List<T> dest, List<S> src){...}
}

This is fine, but while the first type parameter is used both in the type of dst and in the bound of the second type parameter, S, S itself is only used once, in the type of src - nothing else depends on it. This is a sign that we can replace S with a wildcard.

Using wildcards is clearer and more concise than declaring explicit type parameters, and should therefore be preferred whenever possible. Wildcards also have the advantage that they can be used outside of method signatures, as the types of fields, local variables and arrays.
Here is an example on this. Returning to our shape drawing problem, suppose we want to keep a history of
drawing requests. We can maintain the history in a static variable inside class Shape, and have drawAll() store its incoming argument into the history field.

static List<List<? extends Shape>> history = 
new ArrayList<List<? extends Shape>>();
public void drawAll(List<? extends Shape> shapes) {

history.addLast(shapes);
for (Shape s: shapes) {
s.draw(this);
}

}