14.07.2013 Views

Contents - Cultural View

Contents - Cultural View

Contents - Cultural View

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Generics in Java 126<br />

The use of wildcards above is necessary since objects of one type parameter cannot be converted to objects of<br />

another parameter. Neither List nor List is a subtype of the other, even though Integer is a<br />

subtype of Number. So, code that deals with List does not work with List. If it did, it would be<br />

possible to insert a Number that is not a Integer into it, which violates type safety. Here is a sample code that<br />

explains the contradiction it brings if List is a subtype of List:<br />

List ints = new ArrayList();<br />

ints.add(2);<br />

List nums = ints; //valid if List is a subtype of List accordin<br />

substitution rule.<br />

nums.add(3.14);<br />

Integer x=ints.get(1); // now 3.14 is assigned to an Integer variable!<br />

The solution with wildcards works because it disallows operations that would violate type safety.<br />

To specify the lower bounding class of a generic element, the super keyword is used. This keyword indicates that the<br />

aforementioned generic type is a super-type of said bounding class. So, List

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!