Call the superclass constructor with a new array or an ArrayList that contains data?

I am trying to call the constructor of a superclass, either ArrayList (preferred) or an array that already has information. I do not know what my syntax error is, or if you can even do it?

I specifically want to insert "true" and "false" in any object. Only these two.

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

I have a feeling that this is facepalm-er, but I just can't figure it out. I tried different ways, but the pain is that the super constructor MUST be called first, which prevents me from initializing the data.

+4
source share
4 answers

Use the format:

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

if MultipleChoiceQuestion contains a constructor similar to this:

 MultipleChoiceQuestion(String[] questionArray) 

If it contains an overloaded constructor with a List argument, as you say, for example:

 MultipleChoiceQuestion(List<String> questionList) 

then you can use:

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

or if you want to use an ArrayList :

 super(new ArrayList<String>(Arrays.asList(new String[] { "true", "false" }))); 
+7
source

If you have control over the MultipleChoiceQuestion class, you can change the constructor instead:

 public MultipleChoiceQuestion(String ... values) {} 

Then you can call it like this:

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

This is called varargs if you have not heard of them before. You can read about it here: http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

+4
source
 super(new String[]{"true", "false"}); 
+3
source

For a List (not specifically ArrayList ) you can do this:

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

If you need an Arraylist<String> specifically, you will need to do this:

 super(new ArrayList<String>(Arrays.asList(new String[]{"true", "false"}))); 
+2
source

Source: https://habr.com/ru/post/1445392/


All Articles