【问题标题】:How to best add a new object to An array within another object?如何最好地将新对象添加到另一个对象中的数组?
【发布时间】:2017-05-26 14:43:36
【问题描述】:

我有以下对象:

public class Person {

    private String id;

    private Score[] scores;

    public Person() {
    }

    //getters and setters etc


}

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

我打算这样做如下:

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

这是最好的方法吗?

【问题讨论】:

  • 你也必须更新索引...另外,我更喜欢List
  • 对于这样的需求,最好使用一些 List 对象而不是 Array。如果 Array 是必须的,那么您需要正确管理它的创建、当前长度等。

标签: java arrays pojo


【解决方案1】:

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

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

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

【讨论】:

  • 不允许他离开阵列。阅读他之前的问题
  • @XtremeBaumer 如果有他上一个问题的链接会有所帮助。
  • 当我尝试添加 2 个以上的对象时,使用此代码出现 IndexOutOfBounds 异常?请看这个问题:stackoverflow.com/questions/44305231/…
  • 你的初始数组是否足够大?您是否在代码中看到了我的 cmets 关于检查长度和按需增大数组的内容?
【解决方案2】:

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

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,根据您使用的列表执行类似的操作。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 2021-12-28
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 2019-01-18
      相关资源
      最近更新 更多