Java Generic related problems

Java Generic is created for discovering errors in early compilation stage. By using examples, the generic concept can be easily explained. Such kind of questions also appear during interviews.

Problem 1

As a simple example of generic class, Basket contains only one element.

Here the source code:

public class Basket<E> {
 
       private E element;   
 
       public void setElement(E x) {
               element = x;
       }
 
       public E getElement() {
               return element;        
       }
}

We will store fruits in the baskets:

class Fruit { }
 
class Apple extends Fruit { }
 
class Orange extends Fruit { }

What would Java 1.5 do with the following source code?

Basket<Fruit> basket = new Basket<Fruit>(); // 1
basket.setElement(new Apple()); // 2
Apple apple = basket.getElement(); // 3
a)The source code is OK. Neither the compiler will complain, nor an exception during the runtime will be thrown.
b)Compile error in the line 2.
c)Compile error in the line 3.

Answer: c
The line 2 is ok. The line 3 however will cause a runtime error. The result type of the methode getElement of Basket is Fruit. We cannot assign a Fruit to a variable of the type Apple without a cast.

Problem 2

Let's stay with our baskets. What do you think about the following source code?

Basket<Fruit> basket = new Basket<Fruit>();
basket.setElement(new Apple());
Orange orange = (Orange) basket.getElement();
a) source code is OK. Neither the compiler will complain, nor an exception during the runtime will be thrown
b) compile error in the line 2.
c) compile error in the line 3.
d) ClassCastException will be thrown in the line 3.

Answer : d
Both Apples and Oranges are Fruits and can be inserted into a Basket. That is why the cast is necessary in the line 3.
During the runtime the JVM checks the cast in line 3 and throws a ClassCastException since an Apple is not a Orange.

Category >> Generics  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. mr.dude on 2014-1-31

    your genius in explaining something,.. thx

Leave a comment

*