`
linxizeng
  • 浏览: 102239 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Tiger学习 之 可变参数

阅读更多
可变参数,解决Method有不同个数参数的overload问题...
如何创建一个可变长度的参数,看代码:
引用

public void vararg(String varOne, String varTwo, String...strings ) {}

编译器会把它解析为"public void vararg(String varOne, String varTwo, String[] strings) {}",将"..."创建成一个<argument type>的array。

调用很简单...(零或以上多个参数)
引用

vararg("one","tow"); //可以不传参数
vararg("one","tow","three"); //可以传入一个参数
vararg("one","tow","three",four); //可以传入多个参数

当然,也可以传入一个数组作为参数,如:
引用

public void vararg(int... i) {
for (int ivalue : i) {
System.out.println("the i value is: " +ivalue);
}
}

引用

//调用

int[] i = {1,2,3,4,5,6};
new ObjectB().vararg(i);

输出

引用

the i value is: 1
the i value is: 2
the i value is: 3
the i value is: 4
the i value is: 5
the i value is: 6

当然,如果是接受到一个零长度的list,最好做一个判断,可以抛出IllegalArgumentException异常。

But,有些限制:
1.一个方法只能有一个可变参数(一个省略号)
2.省略号只能写在方法参数列表的最后一个。


迭代可变参数List
将vararg当array来使用...如:
引用

public void vararg(String...strings ) {
for (String str : strings) {
System.out.println("the vararg value is: " +str);
}
}

输出
引用

the vararg value is: One
the vararg value is: Two
the vararg value is: Three

也可以将可变参数存在变量中...
引用

public void vararg(String...strings ) {
String[] arr = strings;[color]//存在数组当中,因为自动将String... strings转成String[] strings.
List list = Arrays.asList(strings);//存在list当中
}

由于Tiger是autoboxing和auto-unboxing,所以,当我们需要使用primitive参数的时候,我们也可以在Method中使用wrapper类型,由于wrapper都是Object类型,因此用Object... object作为参数最好了.
引用

public void vararg(Object... object) {
for (Object o : object) {
System.out.println("the object value is: " +o.toString());
}
}

//调用
引用

Integer[] i = {1,2,3};//只能用Integer,如果用int,print不出来具体的值。。。

String[] str = {"A","B","C"};
ObjectB b = new ObjectB();
b.vararg(i);
b.vararg(str);

结果
引用

//Integer类型
the object value is: 1
the object value is: 2
the object value is: 3
//String类型
the object value is: A
the object value is: B
the object value is: C


还有一个情况出现...例如
引用

String[] str = {"A","B","C"};
System.out.printf("the array values are: %s " , str);

输出是:
引用

the array values are: A

因为只会取str的第一个元素的值...可以这样写
引用

System.out.printf("the array values are: %s " ,(Object)str);


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics