2017-05-26 54 views
-1

我有以下对象:如何最好地将一个新对象添加到另一个对象内的数组?

public class Person { 

    private String id; 

    private Score[] scores; 

    public Person() { 
    } 

    //getters and setters etc 


} 

我想创建,增加了另一个对象为分数array的方法。

我正打算这样做,象下面这样:

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

这是这样做的最好方法是什么?

+1

你也必须更新索引...另外,我更喜欢这里的List。 –

+0

对于这样的需求,最好使用一些List对象而不是Array。如果Array是必须的,那么您需要正确管理其创建,当前长度等。 – Galcoholic

回答

5

创建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() 
} 
+0

他不允许从阵列中移开。读他以前的问题 – XtremeBaumer

+0

@XtremeBaumer它会帮助,如果有一个链接到他以前的问题。 –

+0

@AndyTurner这里https://stackoverflow.com/questions/44204221/how-do-i-empty-a-primitive-array/44204290#44204290 –

0

使用ArrayList,而不是得分[],只是scores.add(得分)

0

要么你STOR E中的数组的当前索引,你这样做:

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根据其列出你使用上做类似的事情。

+0

行动我的不好,更正:) – GioGio

0

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

相关问题