Ravisha
Ravisha

Reputation: 3353

Varargs and argument less method

I am just catching up with java 1.5, (yes i know its too early;) ) . while trying out few exercises on varargs , i just found something strange as below. the code compiles well and the varargs method is invoked only when i supply atleast one parameter. shouldn't this have been compiler error, a method and overloaded method with varargs. Or is there any specific usecase you may think, this scenario will be useful

public class VarargsExample {
    public static void main(String args[]) {    
        test1();
    }

    public static void test1(int... x) {
        System.out.println("AssertionExample.test1(ARRAY METHOD)");
    }

    public static void test1() {
        System.out.println("AssertionExample.test1(PARAM LESS)");
    }

}

PS: tried to search this in SO, could not find similar one. pardon me if there is one already:)

Summary, thanks all for your quick responses. seems to be the normal methods are the one preferred. Same is the case when a single param method is present as below

public class VarargsExample{  
 public static void main( String args[] ){  


  test1(); 
  test1(2); 
 } 

 public static  void test1(int... x){
     System.out.println("AssertionExample.test1(ARRAY METHOD)");
 }

 public static  void test1(int x){
     System.out.println("AssertionExample.test1(single param METHOD)");
 }

 public static void test1(){
     System.out.println("AssertionExample.test1(PARAM LESS)");
 } 

}  

Upvotes: 0

Views: 550

Answers (1)

Hoopje
Hoopje

Reputation: 12952

First of call, the parameter-less overloading gets called because its signature is more specific than that of the overlauding with varargs. It is in general a very bad idea to have two overloaded methods which perform a completely different operation. So let's assume that the parameter-less method does the same thing as the varargs method when called without arguments, that is, the parameter-less method is a specialization of the varargs method.

Then a use-case is the following. Calling a varargs method always requires creating an array. Although, certainly at first, I wouldn't think about such minor optimizations too much, but it is an overhead which might, in some cases (for example in tight loop), be considerable enough. The parameter-less version of the method does not require creating an array, and additionally also may contain other optimizations for the specific case.

Sometimes, one sees more than one specializations, one with no arguments, one with one, one with two, and a general method. For example:

void doSomething() { ... }
void doSomething(String a1) { ... }
void doSomething(String a1, String a2) { ... }
void doSomething(String... as) { ... }

But I suggest to only do this in a late stage of development, if at all.

Upvotes: 3

Related Questions