使用包含数据的新Array或ArrayList调用超类的构造函数?

iaa*_*acp 4 java arrays inheritance constructor arraylist

我试图调用一个超类的构造函数,使用ArrayList(首选)或已经包含信息的数组.我不知道我的语法错误是什么,或者你甚至可以做到这一点?

我特别想在任一对象中插入"true"和"false".就是那两个.

public class TrueFalseQuestion extends MultipleChoiceQuestion
{
    Answer myAnswer;
    StringPrompt myPrompt;

    //I can create, but not initialize data up here, correct?
    //Tried creating an ArrayList, but cannot insert the strings before calling constructor

    public TrueFalseQuestion()
    {
        /* Want to call parent constructor with "true" and "false" in array or ArrayList already*/
        super(new String["true", "false"]);
        ...
    }
Run Code Online (Sandbox Code Playgroud)

我有一种感觉,这是一个facepalm-er,但我无法弄明白.我尝试了各种各样的方法,但痛苦的是超级构造函数必须首先被调用,因此没有给我机会初始化数据.

Rei*_*eus 7

使用格式:

super(new String[] {"true", "false"});
Run Code Online (Sandbox Code Playgroud)

如果MultipleChoiceQuestion包含这样的构造函数:

MultipleChoiceQuestion(String[] questionArray)
Run Code Online (Sandbox Code Playgroud)

如果它包含一个带有List参数的重载构造函数,例如:

MultipleChoiceQuestion(List<String> questionList)
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

super(Arrays.asList("true", "false"));
Run Code Online (Sandbox Code Playgroud)

或者如果要求ArrayList使用:

super(new ArrayList<String>(Arrays.asList(new String[] { "true", "false" })));
Run Code Online (Sandbox Code Playgroud)

  • `Arrays.asList`返回`List`,而不是`ArrayList`.(在当前实现中,返回的实际对象不是`ArrayList`的实例;它是私有类`Arrays.ArrayList`的实例.) (2认同)