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

时间:2017-05-26 14:43:36

标签: java arrays pojo

我有以下对象:

public class Person {

    private String id;

    private Score[] scores;

    public Person() {
    }

    //getters and setters etc


}

我想创建一个方法,将另一个对象添加到分数array中。

我打算这样做,如下所示:

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

这是最好的方法吗?

3 个答案:

答案 0 :(得分:4)

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

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

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

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

如果需要坚持使用数组,则必须保留上一个插入位置的一个附加值,例如

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()
}

答案 1 :(得分:0)

要么存储数组的当前索引,你要这样做:

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++;
    }
}

或者正如某人已经说过的那样,你使用的是一个列表,基本上是一个ADT,根据你使用的列表做类似的事情。

答案 2 :(得分:0)

如果您仍想使用它,则需要关注数组大小。首先,当空间不足以放置您的值时,您需要应用数组大小​​。其次,您需要将原始元素复制到新数组。
所以,使用数组的方式不是最好的方法。正如有人已经说过的,最好的方法是使用java类的列表。列表的大小可以动态增长,您不需要关心空间。

相关问题