Henry Wong wrote:
Shanky Sohar wrote:
what i actually mean is why do we have
List<? extends T>
Where we are actually using this in a real time sceneria.
How about a method to add up all numbers from the list? And you don't care if the caller passes a List<Integer>, List<Float>, or List<Double>? By having your parameter be of type List<? extends Number>, you can take any of the three list types and calculate the sum.
Henry
Dan Drillich wrote:
Shanky Sohar wrote:
I am really confused with the use of List<?>....
The Need for Generics says -
The motivation for adding generics to the Java programming language stems from the lack of information about a collection's element type, the need for developers to keep track of what type of elements collections contain, and the need for casts all over the place. Using generics, a collection is no longer treated as a list of Object references, but you would be able to differentiate between a collection of references to Integers and collection of references to Bytes. A collection with a generic type has a type parameter that specifies the element type to be stored in the collection.
As an example, consider the following segment of code that creates a linked list and adds an element to the list:
LinkedList list = new LinkedList();
list.add(new Integer(1));
Integer num = (Integer) list.get(0);
As you can see, when an element is extracted from the list it must be cast. The casting is safe as it will be checked at runtime, but if you cast to a type that is different from, and not a supertype of, the extracted type then a runtime exception, ClassCastException will be thrown.
Using generic types, the previous segment of code can be written as follows:
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(new Integer(1));
Integer num = list.get(0);
Here we say that LinkedList is a generic class that takes a type parameter, Integer in this case.
Atul Darne wrote: