Possible to add more values to a full array?

2019-08-30 11:23发布

问题:

Imagine you have set array words to size 10. You call a method add(String word) ten times which adds 10 words to the array words.

Imagine a user is asked how many words they want to add to an array (int n). I save this value, and create an array words of size n. A method add(String word) is called n times to add 10 different words to the array words. The user is then asked how many more words they want to add (int k). The method add(String word) is then called k more times. But array words is already full of words, and arrays are immutable, so I cant add any more words to that array. How would you go about this problem? Keeping in mind, there is no way of saving the users second value k, I can only access n, so I am also finding it difficult to create a new array of size k, because I don't know what size k is, and I am not meant to know. I know this problem could be easily solved using ArrayLists etc, but I have to use arrays.

So basically, I need to add k more words to array of size n.

My Code so far works for adding the first n words, but when it comes to adding the next k words, I get ArrayIndexOutOfBoundsException(k)...

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

any help? I know it may not even be possible btw lol

回答1:

You will have to do something like

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

But the sane solution would be to use a ArrayList and not a array



回答2:

If you can't use a List, then you have to reallocate your array manually as appropriate:

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

In the snippet above, when the array runs out of space, I create a new array that is 1.5x as large. This is also how ArrayList operates, for instance.



标签: java arrays add