Effective Java 42 Use varargs judiciously

时间:2022-09-23 10:28:18

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&period;方法

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

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

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

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

    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. 通过串口设备vid,pid自动获得该设备所对应的串口号

    用C#做串口通讯很方便,因为dotfx2.0已经集成了Serial Port控件,此控件使用上比MSComm控件更简单,当然它也有一个小bug (RecievedBytesThreshold设置有时候 ...

  2. JEECMS v8 发布,java 开源 CMS 系统

    JEECMSv8 是国内java开源CMS行业知名度最高.用户量最大的站群管理系统,支持栏目模型.内容模型交叉自定义.以及具备支付和财务结算的内容电商为一体:  对于不懂技术的用户来说,只要通过后台的 ...

  3. struts配置通配符&ast;来匹配方法,实现动态调用

    01:web.xml中配置,启动struts2 <?xml version="1.0" encoding="UTF-8"?> <web-app ...

  4. Linux 获取文件时间信息 判断文件是否存在

    获取文件时间戳   (1)查看全部信息: stat e4.txt 范例: [root@localhost ~]# stat e4.txt File: “e4.txt” Size: 0 Blocks: ...

  5. codeforces 651B Beautiful Paintings

    B. Beautiful Paintings time limit per test 1 second memory limit per test 256 megabytes input standa ...

  6. List&lt&semi;T&gt&semi;用法总结【转】

    List<T>用法总结 static void Main(string[] args) { Person p1 = new Person( "aladdin" , 20 ...

  7. Leetcode 807 Max Increase to Keep City Skyline 不变天际线

    Max Increase to Keep City Skyline In a 2 dimensional array grid, each value grid[i][j] represents th ...

  8. CentOS 7 源码编译安装 Redis

    1.下载源码并解压 wget http://download.redis.io/releases/redis-4.0.10.tar.gz tar -xzf redis-4.0.10.tar.gz cd ...

  9. java面向对象编程(六)--四大特征之继承

    本文将介绍继承.方法重载和方法覆盖.其中方法重载和方法覆盖是在讲多态时必须要清楚的一个知识点. 一.继承 1.继承的概念 继承可以解决代码复用,让我们的编程更加靠近人类思维.当多个类存在相同的属性(变 ...

  10. Curl 基本命令

    下载单个文件,默认将输出打印到标准输出中(STDOUT)中 curl http://www.centos.org 通过-o/-O选项保存下载的文件到指定的文件中:-o:将文件保存为命令行中指定的文件名 ...