Array expand doesn't always work?

The example given for ‘expand’ works alright, but the code below is the example for loadStrings, with expand added. Why doesn’t it expand the array?

String[] lines = loadStrings("list.txt");
println("there are " + lines.length + " lines");
for (int i = 0 ; i < lines.length; i++) {
  println(lines[i]);
}
println(lines.length); 
expand(lines, 20);
println(lines.length); 

Output:

there are 5 lines
apple
orange
banana
pear
apricot
5
5

1 Like

Java arrays can’t have its length changed once created. :coffee:

What expand() and other similar functions do is create another array w/ a diff. length, copy the contents of the original array to the new 1, and then return the new 1. :face_with_monocle:

So we do need to store the newly returned array to some variable. :flushed:

That’s why an ArrayList, or in your particular case a StringList, is a much better choice as a dynamic length container: :bulb:

  1. Processing.org/reference/ArrayList.html
  2. Processing.org/reference/StringList.html
  3. Forum.Processing.org/two/discussion/8080/why-use-arraylist-instead-of-array-with-append
1 Like

Yes, thanks, just realised I should have ’ lines = expand(lines, 20); ’

I’ve used ArrayList lots of times, it’s very good.