Search code examples
javacompiler-errorsvariadic-functionsambiguityjava-5

Concept of varargs and ambiguity?


Here's an example:

package com.demo;
public class PassArray {
    static void vaTest(int... v){
        System.out.println("no of args : "+v.length+"contents: ");
        for (int x:v){
            System.out.println(x+" ");
        }
    }
    static void vaTest(boolean... v){
        System.out.println("no of args : "+v.length+"contents: ");
        for (boolean x:v){
            System.out.println(x+" ");

        }
    }
    public static void main(String args[]){

        vaTest(1,2,3);
        vaTest(true,false,true);
        vaTest();//Error:Ambiguous!
    }
}

Can anyone tell me :

I have some Question

1.Why ambiguous error occure ?

2.i have one Varargs parameter just like

int doIt(int a,int b,int c,int... vals)

Why varargs must be declared last ?

  1. What is varargs and ambiguity ?

Solution

  • Since there are two legal method invocations to the call vaTest();, the compiler can't figure out which one to use.
    To help it out, you can provide an empty array of the chosen type:

    vaTest(new int[] {});
    

    More info is available in the JLS 15.12.2.5. Choosing the Most Specific Method.