2014-11-13

Level Up - Java: What is Vararg?

I like to remember vararg as "variable-length arguments". You may see them parameterized as "foo(Object... objects)" or "foo(int... ints)" or maybe "main(String... args)". The triple-dot signifies the vararg, and the method that has them uses it as an array.

Example code:

/** Returns input as a comma-separated list. If input if null
  * or empty, then this returns an empty string. */
public static String convertToString(Object... objects) {
    if (objects == null || objects.length == 0) { return ""; }
    StringBuilder sb = new StringBuilder();
    for (Object object : objects) {
        sb.append(object.toString()).append(", ");
    }
   return sb.substring(0, sb.length() - 2).

No comments: