-2

I would like to create a method that will, sometimes have two arguments passed to it, but only one at other times without passing a null (empty) argument. I know I could do method overloading, but I was looking for a feature like below, without the need for iteration later on:

class MyObject {

    int id;
    int[] zero_Or_MoreArguments;

    Animal(int id, int... zero_Or_MoreArguments) {
        this.id = id;
        this.zero_Or_MoreArguments = zero_Or_MoreArguments;
    }
}

Is there such a thing in Java? Do I have any options here? Thanks in advance.

Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142
  • possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – ArunRaj Mar 03 '15 at 06:29
  • *without passing a null* - No. You will have to atleast pass null. – TheLostMind Mar 03 '15 at 06:31
  • 1
    Did you actually try that code you posted? It works as is (once you declare a proper return type to your Animal method, unless it's a constructor, in which case it should match the name of the class) – Eran Mar 03 '15 at 06:32
  • 1
    @TheLostMind No, with varargs you don't have to pass a null. – Eran Mar 03 '15 at 06:33
  • Eran - I'd like to avoid iterating through `zero_Or_MoreArguments` later on. Is that possible? – Program-Me-Rev Mar 03 '15 at 06:38
  • @Eran - I know.. But he will get an *Empty array* instead of `null` in the his method. So `zero_Or_MoreArguments` will be an empty array. Yes, again I know this will be a good example of *Null Object Pattern* but I think the OP was expecting the value to be `null` when he doesn't pass the array :) – TheLostMind Mar 03 '15 at 06:38

2 Answers2

4

Yes there is, it's called varargs

Modifying your example slightly to show how it works:

class MyObject {

    int id;
    int[] zero_Or_MoreArguments;

    MyObject(int id, int... zero_Or_MoreArguments) {
        this.id = id;
        this.zero_Or_MoreArguments = zero_Or_MoreArguments;
    }

    public static void main(String[]args) {
        MyObject mo = new MyObject(1, 2, 3, 4);
        System.out.println(Arrays.toString(mo.zero_Or_MoreArguments)); // prints [2, 3, 4]
    }
}
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
1

What you need is called variable arguments list.

In Java can be used as:

static void vaTest(String msg, int ... no) {
  System.out.print("vaTest(String, int ...): " +
  msg +"no. of arguments: "+ no.length +" Contents: ");
  for(int  n : no)
  System.out.print(n + " ");
  System.out.println();
}

Complete example at: Java Examples - Use varargs with method overloading

Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142
Xxxo
  • 1,784
  • 1
  • 15
  • 24