What does the term "String ... string" mean in Java?

5

What does the term String... string mean in Java? And how to construct a method that returns a String... as an example:

public String... getStrings(){
     return String... s;)
}

I know it's not that way, but I wanted to know how it works so I can pass it as a parameter in a method like this:

public void setStrings(String... s){
      //codigo
}

Any suggestions?

    
asked by anonymous 01.02.2016 / 14:52

1 answer

7

This is called varargs >.

This is the way to indicate that the last parameter is actually an array of the type mentioned. So the arguments in the method call can have a variable amount. That is, after the fixed and mandatory arguments, can count from zero to "infinite" arguments as long as it is of the declared type.

When accessing s (in your example) remember that this variable is an array and you should access it in this way.

Understand the difference between parameter and argument .

More details on What does the ellipsis in the parameters of a method mean?

Return is not possible in this way, it only serves for parameters. It does not make sense to have something like this, after all this is a syntactic sugar. If you need to return several items you have to use an array or other normal data collection, such as ArrayList or even a previously defined class.

public String[] getStrings(){
     return new String[] {"x", "y"};
}
    
01.02.2016 / 15:08