Java 中有没一种参数语法可即代表 Array 又代表 Collection ?

2014-08-13 07:55:57 +08:00
 andybest
比如 Collection<Deal> deals 与 Deal[] deals
都可以用: for(Deal deal:deals)... 这种方式来遍历,也就是说 for 循环可以同时接受 Collection 与 Array ,它怎么做到的?

我现在有一个方法:
public void process(Deal[] deals)...
我现在想让他也可以处理 Collection ,不得不加一个:
public void process(Collection<Deal> deals)...

有没可能像 for 循环一样,只用一个参数代表这两种形式的可循环(Loopable?)变量?
1937 次点击
所在节点    问与答
8 条回复
vainly
2014-08-13 08:07:42 +08:00
public void process(object deals){
if (details instanceof Collection) {
//process the type of Collection
}

if (details instanceof Array) {
//process the type of Array
}
}
Mutoo
2014-08-13 09:04:07 +08:00
cxe2v
2014-08-13 09:11:27 +08:00
我只晓得在C#里有个IEnumrable接口可以代表这两个类型
andybest
2014-08-13 13:56:26 +08:00
@Mutoo 数组怎么实现 Iterable ?
Mutoo
2014-08-13 17:43:25 +08:00
@andybest 数组本身就是 Iterable 的,你只要用

public void process(Iterable<Deal> deals)

就可以同时传 Collection<Deal> 和 Deal[] 了
andybest
2014-08-13 18:15:10 +08:00
@Mutoo 不行吧?你测试下:

public static void process(Iterable<String> deals){
System.out.println(deals.toString());
}
public static void main(String[] args) {
String[] s1={"aaa","bbb","ccc"};
Collection<String> s2=new ArrayList<String>();
process(s1);
process(s2);
}
Mutoo
2014-08-13 18:37:27 +08:00
@andybest 我错了,我以为 for : 只支持 Iterable, 原来数组不是 Iterable 的 -__-#

http://stackoverflow.com/a/1162255
SoloCompany
2014-08-13 23:48:40 +08:00
for : 是语法糖,Iterable 接口和数组生成的bytcode是不同的。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/127552

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX