0

when I write following code I get error,


List<? extends Number> myList = new ArrayList<>();
myList.add(2);
myList.add(10);

and I know why I get error, because ? means any class that extends Number, which can be Integer, Double, ... so because the type is unspecified I can't add anything to this list. my question is what's the use case for a list which can't have an item in it? The only thing I can think of is at definition time like this :


public List<? extends Number> testMethod()
{
    var x = new ArrayList<Integer>();
    x.add(2);
    x.add(5);
    return x;
}

is that the only use case ?

and my second question is what's difference between two snippets ?

List<? super Number> myList = new ArrayList<>();
myList.add(2);
myList.add(5L);
myList.add(5.5d);
myList.add(3.2f);
System.out.println(myList);

List<Number> myList = new ArrayList<>();
myList.add(2);
myList.add(5L);
myList.add(5.5d);
myList.add(3.2f);
System.out.println(myList);

Majid Abdolhosseini
  • 2,191
  • 4
  • 31
  • 59
  • `List extends Number>` is useful for receiving a list that you can take numbers out of. `List super Number>` is a flexible way of specifying a list that you can put numbers into. – khelwood Mar 30 '20 at 12:54
  • could you please give me a real world example ? when and how would I do so? – Majid Abdolhosseini Mar 30 '20 at 12:56
  • For a real world example of ` extends T>`, look at `ArrayList.addAll`. – Sweeper Mar 30 '20 at 13:01
  • @mhndev [this](https://stackoverflow.com/a/19739576/5515060) answer helped me a lot especially [the image](https://i.stack.imgur.com/KjDLw.png) – Lino Mar 30 '20 at 13:01

0 Answers0