java 可变参数列表 数组_可变参数列表 java

Thinking in Java(3)

1. 可变参数列表

1.1 使用Object数组参数

import java.util.*;

class A {}

public class VarArgs {

static void printArray(Object[] args) {

for(Object obj : args) {

System.out.println(obj + " ");

}

System.out.println();

}

public static void main(String[] args) {

printArray(new Object[] {new Integer(47), new Float(3.14), new Double(11.11)});

printArray(new Object[] {"one", "two", "three"});

printArray(new Object[] { new A(), new A(), new A() });

}

}

result

47

3.14

11.11

one

two

three

A@69d4c4b7

A@fbf00a9

A@44c45f52

最后一个结果,如果java类没有实现toString()方法的话,那么默认输出类名和地址。

1.2 使用可变参数列表

import java.util.*;

class A {}

public class NewVarArgs {

static void printArray(Object... args) {

for(Object obj : args) {

System.out.println(obj + " ");

}

System.out.println();

}

public static void main(String[] args) {

printArray(new Integer(47), new Float(3.14), new Double(11.11));

printArray(47, 3.14, 11.11);

printArray("one", "two", "three");

printArray(new A(), new A(), new A());

printArray((Object[])new Integer[] {1, 2, 3, 4});

printArray();

}

}

47

3.14

11.11

47

3.14

11.11

one

two

three

A@384e23c3

A@120df416

A@5213d99c

1

2

3

4

从上面可以看出,可变参数列表可以为空。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值