optimus
optimus

Reputation: 349

passing Integer or String array as an argument in java

I am writing a java function which which takes two argument : one is a string type and other could be an array of String, Integer, Float, Double, Boolean or just a String.

In JavaScript it is quite easy to pass any data as an argument, but what are the good solutions in java ?

Upvotes: 5

Views: 9805

Answers (5)

Thilo
Thilo

Reputation: 262860

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) {}

That way, you still have type-safety (which an Object argument does not give you).

Upvotes: 2

Akash Shinde
Akash Shinde

Reputation: 955

As you want second object as any data type array you can do something like this

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

As String,Integer,Float,Boolean all are inherited from java.lang.Object,you can simply pass Object[] as second argument and you pass argument(String,Int,....etc) whatever you want.

Upvotes: 0

Jitendra Pareek
Jitendra Pareek

Reputation: 637

The prototype of method as per your need is as follows :

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

Now in the body part you have to cast the object into the required format by Using Wrapper Classes.

Above implementation will resolve the issue.

Upvotes: 0

Forseth11
Forseth11

Reputation: 1438

In java you can only pass the data defined in by the method. A way around this can be to use Object as an argument. Besides that you can create many methods with the same name, but accepting different arguments. Example:

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

When using Object you need to make sure to check what type it is, so you don't end up trying to use an integer as a string array.

I am quite sure that using Object is not the best way to go and you should use multiple methods with different arguments.

Upvotes: 2

Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

I suppose this is what you want

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

Inside the method body, you will have to handle different objects accordingly

Upvotes: 0

Related Questions