0

How do declare and use parameters in java when not knowing the number and type of paramenters that will be passed...

I want to declare a method something like...

static void method1( ... ) for ( i: parameters ) print( i )
// or
static void method1( int a, ... ) for ( f=a; f < parameters.count(); f++) print( parameters[ i] );

Any ideas ?

ZEE
  • 2,931
  • 5
  • 35
  • 47
  • 1
    Possible duplicate of [Java variable number or arguments for a method](http://stackoverflow.com/questions/2330942/java-variable-number-or-arguments-for-a-method) – Tom Nov 05 '15 at 01:07

2 Answers2

3

You can pass exactly one vararg parameter per method. It has to be the last one and you have to specify the type. The vararg-Parameter will be passed into the method ass array.

public void method(int a, String... varargParam){
    for (int f=a; f < varargParam.length; f++){
        System.out.println( varargParam[f] );
    }
}

You can call the method like this

method(2, "test1", "test2");
method(2, "test1", "test2", "test3");
method(2, new String[]{"test1","test2"});

and so on.

Hendrik Simon
  • 231
  • 2
  • 10
2
public void method(Object... objs){}

This will take any number of arguments of unknown type.

Mark Sholund
  • 1,273
  • 2
  • 18
  • 32