实例化通用对象

时间:2012-12-23 22:02:59

标签: java generics polymorphism

我有一个接受Button2子类型的方法。此方法执行一些计算并创建要放置在ArrayList中的按钮,以便它们以图形方式排列。这是我的代码:

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

它来到这里。我不知道怎么说这一行,因为编译器给了我语法错误。如何创建Button2的子类型按钮?

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

我也试过这个:

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

这也给了我一个错误。如何创建此按钮以添加到我的通用ArrayList?

1 个答案:

答案 0 :(得分:1)

您无法将任何对象(null除外)添加到ArrayList<? extends Button2>,但您只需将ArrayList<Button2>传递给您的函数,然后执行buttonList.add(new Button2(xpos,ypos,width,height))

相关问题