Parameters in Java

Asked

Viewed 49 times

0

Hello, everyone!

I have a question which, apparently, must be simple. I am working on a project where there are several methods with parameters being specified in this way, for example: (String... parametro)

Here an example code

private void metodo(RowWrapper rowWrapper, Coluna... colunas) {}

What does this note mean? Could someone please help me?

2 answers

1

The three points in the last parameter serve to call the method as if it had overloaded versions that accepted at the end of its argument list an arbitrary number of arguments of the parameter type.

For example, say you declared the method: public static void foo(String... strings). The 3 points means that you can call the method both without any string and without more than one, that is, all the calls would work for the method:

foo();
foo("Olá mundo");
foo("1", "2", "3");
  • 2

    Technically speaking it is not an overload, in the sense of creating a different method for each combination of parameters. Overloading methods is something that is done at implementation/compile time, in this case of ellipsis the number of arguments is dynamic and occurs at runtime. Java actually solves this without overloading, transforming the argument list into an array and treating it as an array within the method implementation.

  • Yes, you are right

-2

Let me give you an example.

Class Nome

Private String dado;

Public Nome(){

}

Public void  metodo(String teste){
dado = teste;
}

class main( usually main program )


Nome nm = new Nome();
String dadoProTest = "foi um teste";
nm.metodo(dadoProTeste);

Now the Name class data gets "was a test".

This command above is an example, my test cannot be accessed from the main class because it is private, so to assign data to it I have q use "method()" and this value passed inside it and used to store the data, in this example was created a test string, and through that string I passed a value to the dice. In the other I passed it under the name of "dateProTeste" but Java automatically recognizes that the "dateProTeste" is the "test" because it is in the first position ( it is not required to put the same name ) , if it has more than 1 item, ex: method(String test, String teste2)Wherever you go to call you have to follow the order.

  • 2

    Hello. You explained the passage of arguments to the method but when you have the ellipsis in the last argument. To understand see the response linked by hkotsubo.

  • Rectifying: *but not

Browser other questions tagged

You are not signed in. Login or sign up in order to post.