Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wild card ? extends Number in return of a method ?

 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static List<? extends Number> get()
{
List<Integer> list = new ArrayList<Integer>();
list.add(new Integer(4));
list.add(44);
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic