1

When I create a method to determine what value I want to return, usually I can return a value directly - like so:

return 0;

However, I've discovered that when returning arrays, I have to create a new instance of an array, and return it - like so:

String[] rtnArr = {"str1", "str2"}; return rtnArr;

Why is this? Am I creating two arrays here, or am I only specifying a type when I instantiate the method?

Edit: I should clarify that I am returning one or another array based on a preliminary condition. That is to say, I have a switch and each case returns an array of different strings.

Wolfish
  • 960
  • 2
  • 8
  • 34
  • This depends on how you're getting or building the data in the array to begin with. Sometimes you do build a new array; other times you can export it from a collection. How are you building this data out? – Makoto Dec 03 '16 at 19:41
  • 1
    check this answer: http://stackoverflow.com/a/35703309/982161 – ΦXocę 웃 Пepeúpa ツ Dec 03 '16 at 19:48

3 Answers3

0

You are not creating two arrays. Array initializers are only allowed when initiating a variable, so you can't use them directly in a return statement.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You don't actually need a variable to return an array. You can also return an array like this

return new String[] {"Hello", "World"};

When you declare an array you can initialize it as String test[] = {"Hello", "World"}; because the array is obviously a string array so you don't need to do new String[] {"Hello", "World"}, but otherwise, you need an explicit initialization of the array with a type for type safety.

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
0

I've discovered that when returning arrays, I have to create a new instance of an array, and return it Why is this ? Am I creating two arrays here, or am I only specifying a type when I instantiate the method ?

You don't need to return a new instance of the array always, sometimes you might need to return an existing array object as shown in the below code:

public class MyArrayTest {

     private String[] myArray;

     public MyArrayTest(String[] myArray) {
         this.myArray = myArray;
     }

     public String[] getMyArray() {
         return myArray;//returning existing array object
     }
}
Vasu
  • 21,832
  • 11
  • 51
  • 67