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.
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.
So we do need to store the newly returned array to some variable.
That’s why an ArrayList, or in your particular case a StringList, is a much better choice as a dynamic length container:
- Processing.org/reference/ArrayList.html
- Processing.org/reference/StringList.html
- 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.