This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Wild card ? extends Number in return of a method ?

Pawanpreet Singh
Ranch Hand
Posts: 264
public static List<? extends Number> get()
{
List<Integer> list = new ArrayList<Integer>();
return list;
}

public static void main(String args[])
{
//compiler error (1)
List<Number> list1 = get();
}

i know that get() return type is absolutly right but how to get the return value, what reference we need to use in main method

Could anybody help me here

}

Joni Salonen
Ranch Hand
Posts: 53
Suppose the compiler let you do that and that you now have a List of Numbers in list1. Now lets say you want to add a Number to the list, let's say.... new Double(338.67). There's no one stopping you, so congratulations, you now have put a Double in a List that was originally supposed to consist of Integers.

You can fix the compiler error by using "? extends Number" instead of "Number" but remember that you still can't add anything to the list.

Pawanpreet Singh
Ranch Hand
Posts: 264
Thanks a lot

Barry Gaunt
Ranch Hand
Posts: 7729
Here's my take on this (from what I understand from Angelika Langer's Generics FAQ):

The reason List<? extends Number> cannot be assigned to List<Number> is that List<? extends Number> represents a whole family of types, and you cannot assign a family to one specific member of that family.

Aniket Patil
Ranch Hand
Posts: 218
How about asigning List<? extends Integer> to List<Integer>. There's no danger of adding a Double to a List<Integer>, since Integer is final. Hence, there is no family of types that can possibly be added to List<? extends Integer> as it can be to List<? extends Number>.

But this still doesen't work out. Why so?

Barry Gaunt
Ranch Hand
Posts: 7729
How about assigning List<? extends Integer> to List<Integer>?

As you noticed this is not allowed either. List<Integer> is a subtype of List<? extends Integer> (The Java Programming Language, 4th Edition p. 258) and the assignment of a reference to a supertype to a reference of a subtype is not allowed.

You can cast a List<? extends Integer> reference to a List<Integer> reference - but you then get an "unchecked" warning.