The short answer is: don't use an array, always use an array list. The only exception to this is if you absolutely need to control the amount of memory used or you have some specific performance constraint that only String[]
can support.
In general, though, arrays are terrible to work with in an object oriented language, and almost always for the same reason: they make it very easy to break encapsulation. For example:
public class ExampleArray {
private final String[] strings;
public ExampleArray(String... strings) { this.strings = strings; }
public String[] getStrings() { return strings; }
}
See any problems? Yea, you need to write getStrings()
like this:
// ...
public String[] getStrings() { return Arrays.copy(strings); }
// ...
Otherwise, some caller can get a hold of your class' internal data and start modifying it. The only way to prevent this is to copy it every time a caller wants to see it. As opposed to the right way:
public class ExampleList {
private final List<String> strings;
// ...
public List<String> getStrings() { return Collections.unmodifiableList(strings); }
}
Now you're not copying the data, you're just sticking it behind an API that doesn't allow changes. If you use the Guava Immutable*
classes, even better.