Insomani4c
Insomani4c

Reputation: 23

Printing String[] produces random null values, unsure why it's happening

I tried finding this problem on this site, and the closest similar thread was this:

Can't figure out why im getting null values in my array print statement

Basically, I have an instance variable array of Strings taking words from a dictionary.txt file whenever its method is called (I have a separate main method). I have it set up to create a new array with double the capacity whenever it reaches its limit:

public String[] lengthN (int n) {
    /*String[] output = new String[1000];*/
    int i = 0;
    while (input.hasNext()) {
        String word = input.next();
        if (i == output.length) {
            increaseSize();
        }   
        if (word.length() != n) {

        }
        if (word.length() == n) {
            output[i] = word;
            /*System.out.println(output[i]);
            System.out.println(i);*/
            i++;
        }
    }
    for (int j = 0; j < output.length; j++) {
        System.out.println(output[j]); //for testing purposes,returns random null values
    }   
    return output;
}

public void increaseSize() {
      String[] temp = new String[output.length + 1000];
      for (int i = 0; i < output.length; i++) {
          temp[i] = output[i];
          output = temp;
      }    
}

Thankfully, it actually runs and prints out this list. However, in addition to these words, it appears as though large chunks of my list are replaced with null values.

The output itself is too long to post here (with >10000 elements or so), but essentially it is along the lines of

aardvark
null
null
null
null
//lots of null values dispersed throughout
vindicate
vineyards
vintagers
null
null
null
null

If anyone could help point me to a way to fix this problem, I'd be incredibly appreciative! (Apologies if I didn't explain well, first time posting here).

Upvotes: 2

Views: 432

Answers (1)

khelwood
khelwood

Reputation: 59112

Here:

public void increaseSize() {
      String[] temp = new String[output.length + 1000];
      for (int i = 0; i < output.length; i++) {
          temp[i] = output[i];
          output = temp; // <-- here
      }    
}

you are setting the output array variable to the temp array inside your loop. On subsequent iterations through the loop, output and temp are referencing the same array, so temp[i] = output[i] does nothing. Presumably you meant something like this:

public void increaseSize() {
      String[] temp = new String[output.length + 1000];
      for (int i = 0; i < output.length; i++) {
          temp[i] = output[i];
      }
      // Once the loop is finished, and the whole contents have been copied, use the `temp` array as the new `output`.
      output = temp;
}

That should work pretty much the same as just having:

output = Arrays.copyOf(output, output.length+1000);

Upvotes: 5

Related Questions