zoukankan      html  css  js  c++  java
  • Effective Java 42 Use varargs judiciously

    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.

       

  • 相关阅读:
    java 学习
    dubbox 学习
    无能的力量 -- 《看见》
    idea 学习
    小问题?
    《密码学》换字式密码破解。(2)
    《密码学》换字式密码、多表替代密码和转置式密码。(1)
    《密码学》 凯撒密码和栅格密码(0)
    Windows 常用消息及含义
    WM消息大全
  • 原文地址:https://www.cnblogs.com/haokaibo/p/use-varargs-judiciously.html
Copyright © 2011-2022 走看看