0

I have a method that accepts a subtype of Button2. This method does some calculations and creates buttons to be place in an ArrayList so that they are arranged in a graphical way. Here's my code:

public void createButtonArray(ArrayList<? extends Button2> buttonList,
        int xLength, int yLength, int width, int height, int inset) {

    // The total size for the inset, or spaces between buttons
    int totalInset = (xLength - 1) * inset;
    // The total height = height of buttons + size of insets
    int totalHeight = totalInset + 5 * height;
    // ... More calculations

The it comes to this. I don't know how to say this following line because the compiler gives me syntactical errors. How do I create a button that's a subtype of Button2?

Button2<?> button = new Button2(xpos, ypos, width, height);
buttonList.add(button);
counter++;

I've also tried this:

buttonList.add(new <? extends Button2>(xpos,ypos,width,height));

which also gives me an error. How can I create this button to add to my generic ArrayList?

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
helsont
  • 4,347
  • 4
  • 23
  • 28
  • possible duplicate of [Instantiating a generic class in Java](http://stackoverflow.com/questions/1090458/instantiating-a-generic-class-in-java) – Mike Samuel Dec 23 '12 at 22:05
  • Every type is a subtype of itself, so `Button2 button = new Button2(...)` will work if `Button2` is a concrete type with a visible constructor. `Button2> button` will not work if `Button2` does not have a type parameter. – Mike Samuel Dec 23 '12 at 22:07
  • Button2 button = new Button2(xpos, ypos, width, height); buttonList.add(button); leads to a compiler error: The method add(capture#1-of ? extends Button2) in the type ArrayList is not applicable for the arguments (Button2) – helsont Dec 23 '12 at 22:10
  • you can only add a list that accepts super-types, not sub-types, of the type you're adding. A list that can have any subtype of `Button2` **added** to it has type `List super Button2>`, while a list that can have any subtype of `Button2` **gotten** from it has type `List extends Button2>`. – Mike Samuel Dec 23 '12 at 22:43
  • see [Covariance and contravariance](http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#Java) for more details. – Mike Samuel Dec 23 '12 at 22:43

1 Answers1

1

You cannot add any objects (except null) into ArrayList<? extends Button2>, but you can pass just ArrayList<Button2> to your function and then do buttonList.add(new Button2(xpos,ypos,width,height)).

tcb
  • 2,745
  • 21
  • 20