0

I'm trying to resize an Array[] using a method named resize(). I think I've coded the method correctly, however the original array does not resize after running it through the method, and I'm not sure what I'm doing wrong.

I've tested that the newArr[] is in fact twice the length of the oldArr[] and contained the values of the oldArr[], but I can't figure out why it's not taking affect to the wordList[] in the main method.

My assignment is to use Arrays and not Arraylists, so using that is out of the question.

infile = new BufferedReader( new FileReader(infileName) );
while (infile.ready()) {

    String s = infile.readLine();
    System.out.println(wordList.length);
    System.out.println(count);
    wordList[count] = s;

    if(s.length() > lenOfLongest)
        lenOfLongest = s.length();

    if(s.length() < lenOfShortest)
        lenOfShortest = s.length();

    count++;

    if(count == wordList.length)
            resize(wordList);
}

private static String[] resize( String[] oldArr ) {
    String[] newArr = new String[oldArr.length * 2];
    System.out.println(newArr.length);

    for(int i = 0;i < oldArr.length; i++) {
        newArr[i] = oldArr[i];
    }

    return newArr;

}

3 Answers3

4
if(count == wordList.length)
        resize(wordList);

should be:

if(count == wordList.length)
        wordList = resize(wordList);

See this answer for more details.

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

As @pad says in his comment: you don't reassing to wordList.

And your resize() method returns a new array. You should therefore reassing wordList.

As a general note, arrays are not resizable in Java.

fge
  • 119,121
  • 33
  • 254
  • 329
0

Because you are not assign the returned array to anything.Must be as follows.

String[] temp = resize(wordList);
Salih Erikci
  • 5,076
  • 12
  • 39
  • 69