Home arrow Blog

vargs and arrays in java

vargs are a cool feature in java that has gained some traction since their availability in JDK 1.5. However, there are some nuances when working with them that if you don’t keep straight, can require quite a bit of Googling to figure out. Since I keep tripping up on this one myself, I figured I would write a quick post as a reminder for myself. In java, when dealing with a method that accepts a variable number of parameters (vargs), if you pass an array in as the parameter, it will be parsed as a list of parameters. Take this example:

public class VargsExample {
    public static void vargMethod(String... names) {
        for(String name:names) {
            System.out.println(name);
        }
    }

    public static void main(String [] args) {
        vargMethod("Michael", "Minella");
        vargMethod("Michael", "T", "Minella");
    }
}

Both of the above method calls to vargMethod work fine. However, what if we have something like this:

public class VargsExample {
    public static void vargMethod(Object... arrays) {

        for(Object array:arrays) {
        	Object [] curArray = (Object []) array;
            System.out.println(curArray.length);
        }
    }

    public static void main(String [] args) {
        vargMethod(new String [] {"Michael", "Minella"});
        vargMethod(new String [] {"Michael", "T", "Minella"});
    }
}

This time that won’t work. Java will parse our array as a list of parameters and essentially call vargMethod the same way we did in the first example. To fix this, we need to cast our arrays to Object. Essentially we want to trick the JVM into thinking that we are only sending a single object over instead of an array. Below is the code as it should be:

public class VargsExample {
    public static void vargMethod(Object... arrays) {
        for(Object array:arrays) {
        	Object [] curArray = (Object []) array;
            System.out.println(curArray.length);
        }
    }

    public static void main(String [] args) {
        vargMethod((Object) new String [] {"Michael", "Minella"});
        vargMethod((Object) new String [] {"Michael", "T", "Minella"});
    }
}

3 Responses to “vargs and arrays in java”

  • Mike Roberts responded:

    Great tips and tricks, thank you,

  • Run 3 responded:

    Thanks for your sharing. Your article is very useful, it gives me more understanding.

  • Dell customer service responded:

    Really great website i want to come again.Please keep posting.

Add your own comment...

Tweets

    Twitter Button from twitbuttons.com