This site requires JavaScript, please enable it in your browser!
Greenfoot back
Kartoffelbrot
Kartoffelbrot wrote ...

2013/7/28

Infinite Parameters

Kartoffelbrot Kartoffelbrot

2013/7/28

#
How can I write a method like the setPaintOrder method, which allows to use as many parameters as you want? And is there a possibility for this method to count how much parameters there are?
danpost danpost

2013/7/28

#
There is a way to do this, but there are certain rules that must be applied: (1) only the last parameter in the defined list can be repeated by an undetermined amount of times (2) all instances of the repeated parameter must be of the type specified (3) you must use the elipse ('...') to declare the parameter as being an array of the type given For example, the setPaintOrder method declaration could look something like this:
public void setPaintOrder(Class... class)
Then, you can get the number of classes given using 'class.length' and get the value of each class with 'class', where 'n' is an integer between zero and 'class.length - 1'. Basically, you treat it like an array.
Kartoffelbrot Kartoffelbrot

2013/7/28

#
Thank you very much!
Kartoffelbrot Kartoffelbrot

2013/7/29

#
Can I limit that? For example: 0 to 20 parameters are allowed.
davmac davmac

2013/7/29

#
You can't limit it statically, no. Of course you can have your method check the number of parameters and throw an exception if there are too many. if (params.length > 20) { throw new IllegalArgumentException("Too many parameters supplied"); }
Kartoffelbrot Kartoffelbrot

2013/7/29

#
Thanks
You need to login to post a reply.