Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way of passing unknown number of strings to a function in java

Tags:

java

string

I want to pass a diffrent number of strings to a function in java, it suppose to be the strings to filter a query by, it could be 2-4 strings.

What do you think will be the best way to do that?

a) creating an overload for the same function with different number of parameters? b) create a new instance of an array of string and pass it to the function?

any other preffered way?

thanks

like image 396
Doron Sinai Avatar asked Nov 14 '10 12:11

Doron Sinai


People also ask

How do you pass string values?

To pass a string by reference, IDL passes the address of its IDL_STRING descriptor. To pass a string by value, the string pointer (the s field of the descriptor) is passed.

How do you pass a string to a method in Java?

Method signaturepublic static void myMethod(String fname) ; The method takes the String parameter and then appends additional text to the string and then outputs the value to the console. The method is invoked from the method by passing some sample strings with male names.

How do you pass two strings in Java?

If you don't have any argument other that single String then you can pass delimited string to that method e.g. and then inside the method use String#split to split the passed String into array or List. PS: Just make sure that chosen delimiter doesn't appear inside the string values.

Why Java is strictly pass by value?

Object references are passed by value The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.


1 Answers

Java has supported variable argument lists since 1.5:

public void myMethod(String... values)
{
    for (String val : values)
    {
        // do something
    }
}

The rules are simple:

  • The variable argument must be the last argument in the method signature.
  • It's a single argument, so all values will be of the same type.
  • Inside the method, the vararg appears to be an array.
  • When calling the method, you can either pass individual values or an array.
like image 107
Anon Avatar answered Sep 23 '22 08:09

Anon