0

I have two options and both have (afaik) the same output:

// 1
array = arrayList.toArray(new T[0]);
// 2
array = new T[arrayList.size()];
arrayList.toArray(array);

The first is shorter.

Is there any reason to use the second?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • 2
    Does this answer your question? [.toArray(new MyClass\[0\]) or .toArray(new MyClass\[myList.size()\])?](https://stackoverflow.com/questions/174093/toarraynew-myclass0-or-toarraynew-myclassmylist-size) – Amongalen Dec 06 '19 at 09:47
  • @Amongalen do you know why the accepted answer says 1 is faster, but the second (most highly-voted answer) suggests 2 is faster? Which is actually faster... – theonlygusti Dec 06 '19 at 09:52
  • One of the comments on that second answer says "This is no longer valid answer as of JDK6+". There is 7 years difference between those two answers, there was a lot of changes in the Java itself and in JVMs. Perhaps you could run those benchmarks yourself on the current versions to check if anything changed. Anyway, in most cases such microoptimalization is not worth it. – Amongalen Dec 06 '19 at 09:59

0 Answers0