【问题标题】:Possible to add more values to a full array?可以向完整数组添加更多值吗?
【发布时间】:2013-12-06 15:09:36
【问题描述】:

假设您已将数组单词的大小设置为 10。 您调用方法 add(String word) 十次,将 10 个单词添加到数组 words 中。

想象一个用户被问到他们想要添加多少个单词到一个数组(int n)。 我保存这个值,并创建一个大小为 n 的数组单词。 方法 add(String word) 被调用 n 次以将 10 个不同的单词添加到数组 words 中。 然后询问用户他们还想添加多少单词(int k)。 然后方法 add(String word) 被调用 k 次。 但是数组 words 已经充满了单词,并且数组是不可变的,所以我不能再向该数组添加任何单词。 你会如何解决这个问题? 请记住,没有办法保存用户的第二个值 k,我只能访问 n,所以我也发现很难创建一个大小为 k 的新数组,因为我不知道大小 k 是多少,并且我不想知道。 我知道使用 ArrayLists 等可以轻松解决这个问题,但我必须使用数组。

所以基本上,我需要在大小为 n 的数组中再添加 k 个单词。

到目前为止,我的代码适用于添加前 n 个单词,但在添加接下来的 k 个单词时,我得到 ArrayIndexOutOfBoundsException(k)...

公共类 WordStoreImp {

private int counter=0;
private int size;
private String words[];

public WordStoreImp(int n)
{
    size=n;
    words=new String[n];
}

public void add(String word)
{
    words[counter]=word;   
    counter++;
}

有什么帮助吗?我知道这可能甚至不可能顺便说一句哈哈

【问题讨论】:

  • "数组是不可变的" -- 不是这样。
  • 您需要调整数组的大小(如果手动完成,则复制原始数据)。
  • 如果您打算使用数组而不是集合,请调查System.arrayCopy() 请参阅:docs.oracle.com/javase/7/docs/api/java/lang/System.html
  • 您必须创建一个具有新大小的新数组并从原始数组复制元素。
  • 利用Arrays.copySystem.arraycopy()

标签: java arrays add


【解决方案1】:

你将不得不做类似的事情

public void add(String word)
{
    if (counter >= words.length){
        String[] newWords=new String[counter + 1];
        for(int i=0; i<words.length; i++){
             newWords[i]=words[i];
        }
        words = newWords;
    }
    words[counter]=word;   
    counter++;
}

但理智的解决方案是使用 ArrayList 而不是数组

【讨论】:

  • 谢谢,这似乎工作正常。非常感谢队友
  • 将大小仅增加 1 是个坏主意。这意味着超过初始限制的个添加都需要完全重新分配和复制数组。
  • ArrayList 在超出容量时将数组的大小加倍。这导致 add() 的 O(1) 摊销复杂度。不会持续增长。
【解决方案2】:

如果您不能使用List,那么您必须根据需要手动重新分配您的数组:

public void add(String word) {

    if (counter < words.length) {
        words[counter] = word;   
    } else {
        String[] newWords = new String[(words.length * 3)/2 + 1];  // reallocate

        System.arraycopy(words, 0, newWords, 0, words.length);
        words = newWords;

        words[counter] = word;
    }

    counter++;
}

在上面的 sn-p 中,当数组空间不足时,我创建了一个 1.5 倍大的新数组。例如,这也是 ArrayList 的运作方式。

【讨论】:

  • 为什么要检查计数器是否小于字符串的长度?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 2016-01-31
  • 2018-06-19
  • 2014-01-07
  • 2016-11-04
  • 1970-01-01
  • 2020-04-30
相关资源
最近更新 更多