Java 如何最好地将新对象添加到另一个对象内的数组中?

Java 如何最好地将新对象添加到另一个对象内的数组中?,java,arrays,pojo,Java,Arrays,Pojo,我的目标如下: public class Person { private String id; private Score[] scores; public Person() { } //getters and setters etc } 我想创建一个方法,将另一个对象添加到Scores数组中 我计划这样做,如下所示: public void addScore(Score score){ scores[0] = score; }

我的目标如下:

public class Person {

    private String id;

    private Score[] scores;

    public Person() {
    }

    //getters and setters etc


}
我想创建一个方法,将另一个对象添加到Scores
数组中

我计划这样做,如下所示:

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

这是最好的方法吗?

创建setter方法是个好主意。然而,不知何故,你必须跟踪添加到列表中的分数数量。通过始终将设置值分配给数组索引0,最终将反复替换第一个值

我建议您改为使用一些列表分数-然后您可以将添加项委托给列表:

protected List<Score> scores = new ArrayList<Score>();

public void addScore(Score score) {
  scores.add(score)
} 

要么存储数组的当前索引,然后执行以下操作:

private String id;

private Score[] scores;
private int index;

public Person()){
    index = 0;
    scores = new Score[10];
}
public void addScore(Score score){
    if(index<scores.length){
       scores[index] = score;
       index++;
    }else{
       Score[] temp = new Score[index+10];
       for(int i=0;i<scores.length;i++){
          temp[i] = scores[i];
       }
       scores = temp;
       scores[index] = score;
       index++;
    }
}
私有字符串id;
私人分数[]分;
私有整数索引;
公众人士()){
指数=0;
分数=新分数[10];
}
公共无效添加分数(分数){
如果(指数
如果仍要使用数组,则需要注意数组大小。首先,当空间不足以放置值时,需要应用数组大小。其次,需要将原始元素复制到新数组。


所以,使用数组的方法不是最好的方法。正如有人已经说过的,最好的方法是使用java类的列表。列表的大小可以动态增长,你不需要关心空间。

你也必须更新索引…而且,我更喜欢这里的
列表
。对于这种要求,最好使用一些列表对象而不是数组。如果数组是必须的,那么您需要正确管理它的创建、当前长度等。他不允许离开数组。请阅读他的上一篇文章question@XtremeBaumer如果有一个指向他之前问题的链接,这会有所帮助。@AndyTurner在这里,当我尝试添加两个以上的对象时,我使用此代码得到一个IndexOutOfBounds异常?请看这个问题:您是否使初始数组足够大?您是否看到我在代码中关于检查长度和按需增大数组的注释?
private String id;

private Score[] scores;
private int index;

public Person()){
    index = 0;
    scores = new Score[10];
}
public void addScore(Score score){
    if(index<scores.length){
       scores[index] = score;
       index++;
    }else{
       Score[] temp = new Score[index+10];
       for(int i=0;i<scores.length;i++){
          temp[i] = scores[i];
       }
       scores = temp;
       scores[index] = score;
       index++;
    }
}