5

我正在尝试使用 ArrayList(preferred) 或其中已经包含信息的数组来调用超类的构造函数。我不知道我的语法错误是什么,或者你是否能做到?

我特别想在任一对象中插入“真”和“假”。就这两个。

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"]);
        ...
    }

我有一种感觉,这是一个面部护理,但我就是想不通。我尝试了各种方法,但痛苦是必须首先调用超级构造函数,因此没有机会初始化数据。

4

4 回答 4

8

使用格式:

super(new String[] {"true", "false"});

ifMultipleChoiceQuestion包含这样的构造函数:

MultipleChoiceQuestion(String[] questionArray)

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

MultipleChoiceQuestion(List<String> questionList)

那么你可以使用:

super(Arrays.asList("true", "false"));

或者如果ArrayList需要使用:

super(new ArrayList<String>(Arrays.asList(new String[] { "true", "false" })));
于 2012-11-11T21:10:00.913 回答
4

如果您对 MultipleChoiceQuestion 类有任何控制权,则可以将构造函数更改为此:

public MultipleChoiceQuestion(String ... values) {}

然后你就可以这样称呼它:

public TrueFalseQuestion() {
    super("true", "false");
}

如果您以前没有听说过它们,这称为可变参数。您可以在这里阅读:http: //docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

于 2012-11-11T21:17:49.537 回答
3
super(new String[]{"true", "false"});
于 2012-11-11T21:09:59.197 回答
2

对于 a List(不是特别是 a ArrayList),您可以这样做:

super(Arrays.asList("true", "false"));

如果你特别需要一个Arraylist<String>,你需要这样做:

super(new ArrayList<String>(Arrays.asList(new String[]{"true", "false"})));
于 2012-11-11T21:15:39.517 回答