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.

Effective Java 42 Use varargs judiciously的更多相关文章

  1. Effective Java 11 Override clone judiciously

    Principles If you override the clone method in a nonfinal class, you should return an object obtaine ...

  2. Effective Java 41 Use overloading judiciously

    The choice of which overloading to invoke is made at compile time. // Broken! - What does this progr ...

  3. Effective Java 74 Implement Serializable judiciously

    Disadvantage of Serializable A major cost of implementing Serializable is that it decreases the flex ...

  4. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  5. 《Effective Java》读书笔记 - 7.方法

    Chapter 7 Methods Item 38: Check parameters for validity 直接举例吧: /** * ...其他的被我省略了 * @throws Arithmet ...

  6. Effective Java 第三版——42.lambda表达式优于匿名类

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  7. Effective Java 第三版——32.合理地结合泛型和可变参数

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  8. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  9. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

随机推荐

  1. SQL Server里等待统计(Wait Statistics)介绍

    在今天的文章里我想详细谈下SQL Server里的统计等待(Wait Statistics),还有她们如何帮助你立即为什么你的SQL Server当前很慢.一提到性能调优,对我来说统计等待是SQL S ...

  2. html5中的大纲

    html5中的大纲 前言: 在html5中我们可以使用结构元素来编排一份大纲,这样我们就可以通过这个网页的大纲来了解网页中有哪些内容,网页中以什么样的形式来组织这些内容有更清楚的认识. 1.html5 ...

  3. 百度分页样式代码 css+c#

    通过c#输出html分页代码: /// <summary> /// 返回分页Html代码 /// </summary> /// <param name="pag ...

  4. servlet中的细节

    Get方法有大小限制:1024个字符.这些信息使用 Query_String头传递,并通过Query_String环境变量访问.Post方法:请求体信息使用FromData头传递.读取所有表单参数:g ...

  5. 在GridView列表中使用图片显示记录是否包含附件

    在我的前面很多文章中,都介绍过通用附件模块的管理,本篇随笔主要介绍在一些应用模块中的列表展示中,包含附件的记录,在GridView列表界面中使用图标来快速显示是否有附件的情况. 1.通用附件模块的应用 ...

  6. VisualStudio代码调试输出跟踪

    class EFIntercepterLogging : DbCommandInterceptor { private readonly Stopwatch _stopwatch = new Stop ...

  7. 【Android】将Xamarin For VS升级为4.1.0.530版

    分类:C#.Android.VS2015(自带Update2).Win10 创建日期:2016-06-10 2016-08-03说明:该版本已过时,新版本详见本博客置顶的更新. 一.Xamarin f ...

  8. task 限制任务数量(转自msdn)

    public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler { // Indicates whether the current ...

  9. 【C#进阶系列】10 属性

    属性分为无参属性和有参属性(即索引器). 属性相对于字段的优点不仅仅是为了封装,还可以在读写的时候做一些额外操作,缓存某些值或者推迟创建一些内部对象,也适用于以线程安全的方式访问字段. 话说最基本的属 ...

  10. 状态压缩DP--Mondriaan's Dream

    题目网址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=110044#problem/A Description Squares and ...