-2

I can't seem to find an explanation for this. Does new String[] {} provide a more efficient way of providing the type of array?

halecommarachel
  • 124
  • 1
  • 9

1 Answers1

2

new String[] {} is an empty array, which means toArray would have to create a new String array in order to convert the Collection to an array (unless the Collection is empty, in which case toArray can simply return the empty array that was passed to it).

In most cases c.toArray(new String[c.size()]), which passes the array instance that would be returned by the method, would be slightly more efficient, since one less array object is instantiated compared to c.toArray(new String[] {}).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • So `new String[] {}` is the same as `new String[0]`? How are these the same? – halecommarachel Jul 06 '15 at 06:15
  • Rather, what is the concept behind the first method, so I can read more about it? – halecommarachel Jul 06 '15 at 06:19
  • @halecommarachel `new String[] {}` is exactly the same as `new String[0]`. `new String[] {"x","y","z"}` is a way to instantiate an array without specifying its length explicitly. If you use an empty array `{}` in this initialization, it creates an array of 0 length. – Eran Jul 06 '15 at 06:23
  • @halecommarachel Are you asking about the concept behind this type of array instantiation? It's just one of the ways Java allows you to instantiate an array. It's similar to `String[] arr = {"aa","bb","vv"};` – Eran Jul 06 '15 at 06:25
  • I was just reading the Java trail on arrays and it initializes an array without using `new`, i.e. `String[] sa = {"hello", "world"}`. Do you know if that's a new shortcut or something? – halecommarachel Jul 06 '15 at 06:28
  • Yeah okay the trail doesn't show that method – halecommarachel Jul 06 '15 at 06:29
  • @halecommarachel There's a difference between initializing an array in the same line it is declared (no need for `new`) and initializing it after it's already declared or passing an array to a method without first declaring a variable for it (both require `new`). – Eran Jul 06 '15 at 06:31
  • Got it, thanks for going into that for me. – halecommarachel Jul 06 '15 at 06:32
  • @halecommarachel You're welcome – Eran Jul 06 '15 at 09:20