Search code examples
javaarrayspojo

How to best add a new object to An array within another object?


I have the following object:

public class Person {

    private String id;

    private Score[] scores;

    public Person() {
    }

    //getters and setters etc


}

I would like to create a method that adds another object into the Scores array.

I was planning to do so like below:

public void addScore(Score score){
    scores[0] = score;
}

Is this the best way to do so?


Solution

  • Creating a setter method is a good idea. Yet somehow you'll have to keep track of the number of scores added into your list. By always assigning your set value to array index 0 you'll end up replacing first value over and over.

    I suggest you use some List scores instead - you could then delegate the add to the list:

    protected List<Score> scores = new ArrayList<Score>();
    
    public void addScore(Score score) {
      scores.add(score)
    } 
    

    If you need to stick with an array, you have to keep one additional value of your last insert location like

    protected int lastItem = 0;
    
    protected Score[] scores = new Score[100]; //any initial size
    
    public void addScore(Score score) {
      scores[lastItem++] = score;
      //check if you need to make the array larger
      //maybe copying elements with System.arraycopy()
    }