Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a method which accepts any number of arguments of any type in Java?

I can see there is a way to have a method in Java which accepts any number of arguments of a specified type: http://www.java-tips.org/java-se-tips/java.lang/how-to-pass-unspecified-number-of-arguments-to-a-m.html

but is there a way to make a method which accepts any number of arguments of any type?

like image 386
flea whale Avatar asked Feb 19 '12 23:02

flea whale


People also ask

How do you accept multiple arguments in Java?

The varargs functionality allows you to pass any number of arguments to a method. The method must be set up with the type of data and a variable name to hold the elements. You can add more parameters to the method, but the varargs statement must be the last one.

Can a method accept more than one argument?

We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.

How many arguments can a method have Java?

You can use any number of arguments in a function in java. There is no standard limit to have this number of argument in function in java. [As per I know] IMO as a practice you should not have more than 4 arguments for a function but this is not the standard you can have any number of arguments. Save this answer.


1 Answers

All Java Objects extend the Object class. So you can make your function accept an Object array:

public void func(Object[] args) {
}

Or if you want to be able to pass nothing:

public void func(Object... args) {
}
like image 198
Jivings Avatar answered Nov 13 '22 06:11

Jivings