Java – return immutable list

I'm creating a course called question This class has answers, so I want to be able to return a list of answers attached to it

However, if the user changes the answer, I want the user to call the update method so that I can perform other verifications, etc Now, if the user gets the answer list, he can still change the answer by saying the question (). get(0). setDescription(“BLAH BLAH”).

So I want to reply to a copy of each answer and let the user change this. He must merge / update it back to the question In this way, I can ensure that the answer is valid, but the equals method of the answer is based on the description and the correct field rather than the ID field, because I use JPA If the user changes the answer using this method, the update method will not find the answer because the description field has changed and is no longer equal, so it cannot be found in the list

Any suggestions?

public void updateAnswer(Answer answer) {
    int index = answers.indexOf(answer);
    answers.set(index,answer);
}

public List<Answer> getAnswers() {
    return Collections.unmodifiableList(answers);
}


@Test
public void shouldUpdateAnswerInQuestion() {
    // Get first answer,make an update on the description
    // and then update answer on question.
    Answer answerThatWillBeUpdated = question.getAnswers().get(0);
    String updatedAnswerDescription = "Hey,it is Now updated!";
    answerThatWillBeUpdated.setDescription(updatedAnswerDescription);
    question.updateAnswer(answerThatWillBeUpdated);

    // After updating check that the answer in the list is equal
    // to the answer updated.
    Answer answerFromList = question.getAnswers().get(0);

    assertEquals(answerThatWillBeUpdated,answerFromList);
}

Answer class:

public class Answer {

    private long id;
    private String description;
    private Boolean correct;
    ...
}

Solution

You should reconsider your application design, but since I'm not sure what your domain limitations are, I can't recommend a slight redesign or any type

A simple and clear answer is: program to interface, not implementation If you want to force the update method to be called after modifying the setter, consider using the decorator mode

>Create an interface > let your concrete class implement this interface (answer) > add a concrete class (choose a better name but answerdecorator), which implements the interface that accepts the concrete class in the constructor of the class mentioned above

Then, you only need to delegate all methods to the internal instance and delegate the method to be called to update. Please do the following:

Public void setfield (int a) {innerinstance.setfield (I); update (...);}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>