It does not generate objects of a specific class

0

When I try to use this code I do not generate objects and when printing it says that it is empty.

List<Question> questions = new ArrayList();
ChoicesQuestion q = new ChoicesQuestion();
ChoicesAnswer a = new ChoicesAnswer();
q.setText("La tierra es redonda?");
q.setChoices().add(new Choice("Verdadero", true));
q.setChoices().add(new Choice("Falso", false));
questions.add(q);
System.out.println(q.setChoices().isEmpty());

If you need to see the complete library here: link

    
asked by Brandon Ruiz Morales 03.04.2018 в 04:04
source

2 answers

3

The problem is in the class ChoicesQuestion specifically in the method setChoices since every time you call that method returns a ArrayList empty.

To make your code work, you should do the following:

  • In the property declaration (class ChoicesQuestion) initialize your list of options

    private Collection<Choice> choices = new ArrayList();

  • Then use the getChoices() method to get that reference

    public Collection<Choice> getChoices() { return choices; }

  • It would stay like this:

    List<Question> questions = new ArrayList();
    ChoicesQuestion q = new ChoicesQuestion();
    ChoicesAnswer a = new ChoicesAnswer();
    q.setText("La tierra es redonda?");
    q.getChoices().add(new Choice("Verdadero", true));
    q.getChoices().add(new Choice("Falso", false));
    questions.add(q);
    System.out.println(q.getChoices().isEmpty());
    
        
    answered by 03.04.2018 / 04:17
    source
    0

    Simple Option

    Change this line in your class ChoicesQuestions :

    public Collection<Choice> setChoices() {
    
            return choices;
        }
    

    I have initialized the collection in the constructor

    public ChoicesQuestions () {    this.choices = new ArrayList < > (); }

    Rebooted Option

    Just as you have it, you will create some confusion in the code, but it can be valid to shorten what you write a bit. (Personally I really like doing this in the set but I have found problems with debugging and reading)

    I would change this line in your class ChoicesQuestions :

    public Collection<Choice> setChoices() {
            return new ArrayList<>();
        }
    

    for this one:

    public Collection<Choice> setChoices(Choice choice) {
            choices.add(choice);
            return this;
        }
    

    Not without first initializing the collection.

    private Collection<Choice> choices = new ArrayList<>();
    

    This can also be done in the constructor for added security.

    Then I would call in this way to add continuously:

    q.setChoices(new Choice("Verdadero", verdadero))
     .setChoices(new Choice("Falso", false));
    
        
    answered by 03.04.2018 в 05:51