Passing an Integer or String array as an argument in java

I am writing a java function that takes two arguments: one is the type string

and the other can be array of String, Integer, Float, Double, Boolean

or just string

.

It's pretty easy to pass any kind of data as an argument in JavaScript, but what are some good solutions in java?

+3


source to share


5 answers


You can overload the method to accept different parameters.

 void doSomething(String x, int[] y) {}

 void doSomething(String x, String[] y) {}

 void doSomething(String x, String y) {}

      



This way you still have type safety (which the argument Object

doesn't give you).

+1


source


In java, you can only pass data defined in a method. A way to do this might be to use Object as an argument. Alternatively, you can create many methods with the same name, but accept different arguments. Example:

public void example(String str, Object obj){ /* code */ }

      



When using Object, you need to make sure it is of type, so you are not trying to use an integer as a string array.

I'm pretty sure using Object is not the best way to go and you should use multiple methods with different arguments.

+2


source


I suppose this is what you want

public void method1 (String str, Object ... val)

Within the body of the method, you will have to handle various objects accordingly

0


source


How do you want the second object to be like any array of datatypes you can do something like this

public void _methodName(String arg1,Object[] arg2)

      

As String, Integer, Float, Boolean all inherit from java.lang.Object

, you can just pass as the second argument and pass the argument (String, Int, .... etc) whatever you want. Object[]

0


source


The prototype method according to your needs is the following:

public void testMethod(String strVal, Object[] genericVal)

      

Now in the body part, you must pass the object in the required format using the Wrapper classes.

The above implementation will solve the problem.

0


source







All Articles