代码改变世界

Effective Java 42 Use varargs judiciously

2014-04-05 18:21  小郝(Kaibo Hao)  阅读(476)  评论(0编辑  收藏  举报

Implementation theory

The varargs facility works by first creating an array whose size is the number of arguments passed at the call site, then putting the argument values into the array, and finally passing the array to the method.

   

// Simple use of varargs

static int sum(int... args) {

int sum = 0;

for (int arg : args)

sum += arg;

return sum;

}

   

// The right way to use varargs to pass one or more arguments

static int min(int firstArg, int... remainingArgs) {

int min = firstArg;

for (int arg : remainingArgs)

if (arg < min)

min = arg;

return min;

}

   

Usage

  1. Designed for printf(added in release 1.5).
  2. Core reflection facility, was retrofitted to take advantage of varargs in that release.

   

Note

  1. Don't retrofit every method that has a final array parameter; use varargs only when a call really operates on a variable-length sequence of values.

   

// The wrong way to print an array

public static void main(String[] args) {

int[] digits = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 4 };

System.out.println(Arrays.asList(digits));

/* This will print [[I@2cdb03a1], since The Arrays.asList method, now "enhanced" to use varargs, gathers up the object reference to the int array digits into a one-element array of arrays and dutifully wraps it into a List<int[]>instance. */

}

   

// The right way to print an array

System.out.println(Arrays.toString(digits));

// This will print [ 3, 1, 4, 1, 5, 9, 2, 6, 5, 4]

   

2. Every invocation of a varargs method causes an array allocation and initialization it will introduce the performance issue. There is a pattern to solve this. Suppose you've determined that 95 percent of the calls to a method have three or fewer parameters. Then declare five overloadings of the method, one each with zero through three ordinary parameters, and a single varargs method for use when the number of arguments exceeds three:

   

public void foo() { }

public void foo(int a1) { }

public void foo(int a1, int a2) { }

public void foo(int a1, int a2, int a3) { }

public void foo(int a1, int a2, int a3, int... rest) { }

       3. EnumSet is good example for this which provides performance-competitive replacements for bit fields(Item 32).

   

Summary

Varargs methods are a convenient way to define methods that require a variable number of arguments, but they should not be overused. They can produce confusing results if used inappropriately.