1

I'm trying to add an Integer to an Arraylist with a wildcard that extends Number Class. The compiler gives me an error. I don't know how to solve this problem.

import java.util.ArrayList;

public class WildCard {
    ArrayList<? extends Number> an;

    public WildCard() {
        an = new ArrayList<Integer>();
    }

    public void addI(Integer a) {
        an.add(a);
    }

    public static void main(String[] args) {
        WildCard w = new WildCard();
        Integer b = 3;
        w.addI(b);
    }
}
abdul
  • 21
  • 2

3 Answers3

0

Change wildcard ? to T:

public class Test <T extends Number> {
    ArrayList<T> an;

    public Test(){
        an = new ArrayList<T>();
    }

    public void addI(T a){
        an.add(a);
    }

    public static void main(String[]args){
        Test<Number> w = new Test<>();
        Integer b = 3;
        w.addI(b);

        Test<Integer> w2 = new Test<>();
        Integer b2 = 32;
        w2.addI(b2);
    }
}
0

Impossible.

That's what wildcard means.

You're asking: "How do I find the corner in this circle?" - or "How do I move an immovable object?"

wildcard means: Cannot be added to.

The reason it means that, is highlighted by this simple exercise:

List<Double> doubles = new ArrayList<Double>();
List<? extends Number> whoknows = doubles;
whoknows.add(Integer.valueOf(5));

note that whoknows and doubles are pointing to the exact same list. There is only one list here; whatever you do with the doubles list is also done to whoknows and vice versa.

Soooo, if you find any way at all to add an integer to this, you... just... added an integer. To a list of doubles. uhoh.

Which is why you can't.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • 1
    I disagree with the statement "wildcard *means*: Cannot be added to" It is absolutely possible to add elements to a `List super T>`, i.e., when you have a wildcard with a lower bound. Rather than that, you should explain that it is some type that you do not know about. It's more of "there's an `ArrayList` where T is *some type* that extends `Number`" – user Jul 14 '20 at 15:58
  • 1
    The `? extends` wildcard means 'cannot be added to'. The `? super` wildcard means the reverse. The answer is complex enough as is; an SO answer is properly not the right place for a complete and in-depth treatise on co/contra/and invariance, and how java has implemented these concepts. At least, not unless the SO question is literally 'please explain these concepts to me'. – rzwitserloot Jul 15 '20 at 16:29
  • Oh, no, I didn't mean that you should've explained variances in this answer and all that. The example you've given is great and is probably all you needed - I was just being nitpicky about the meaning of `?` – user Jul 15 '20 at 16:41
-1

Just do it like this and you can add Integer.

ArrayList<Number> an;

instead of

ArrayList<? extends Number> an
unrated
  • 252
  • 4
  • 22