Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input stored in Arraylist or String array? (New programmer) Java

It seems to me like ArrayList would be easier to use in nearly every scenario, it being very versatile. Is there an instance where a String[] would be used to store inputted data? If there is such a case, there must be a drawback in ArrayList, what would that be?

Only thing that comes to mind off the top of my head would be the variety of String methods like, substring() and split(), etc.

EDIT: New to StackOverflow as well. I apologize if this was a re-post. And thanks for the formatting.

like image 627
Mizu Avatar asked Dec 14 '12 07:12

Mizu


2 Answers

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.

like image 99
severoon Avatar answered Oct 07 '22 11:10

severoon


Of course there are situations where you want to use String[] instead. If you know in advance how long the list will be, for instance, and the list might be large.

The main disadvantage of using ArrayList is that as the list grows, the array has to be reallocated, which isn't a free operation. You can mitigate that by preallocating it to be the size (or larger) you expect using the constructor that accepts an initialCapacity.

like image 40
T.J. Crowder Avatar answered Oct 07 '22 12:10

T.J. Crowder