V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
andybest
V2EX  ›  问与答

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

  •  
  •   andybest · 2014-08-13 07:55:57 +08:00 · 1932 次点击
    这是一个创建于 3562 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如 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?)变量?
    8 条回复    2014-08-13 23:48:40 +08:00
    vainly
        1
    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
        2
    Mutoo  
       2014-08-13 09:04:07 +08:00
    cxe2v
        3
    cxe2v  
       2014-08-13 09:11:27 +08:00
    我只晓得在C#里有个IEnumrable接口可以代表这两个类型
    andybest
        4
    andybest  
    OP
       2014-08-13 13:56:26 +08:00
    @Mutoo 数组怎么实现 Iterable ?
    Mutoo
        5
    Mutoo  
       2014-08-13 17:43:25 +08:00
    @andybest 数组本身就是 Iterable 的,你只要用

    public void process(Iterable<Deal> deals)

    就可以同时传 Collection<Deal> 和 Deal[] 了
    andybest
        6
    andybest  
    OP
       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
        7
    Mutoo  
       2014-08-13 18:37:27 +08:00
    @andybest 我错了,我以为 for : 只支持 Iterable, 原来数组不是 Iterable 的 -__-#

    http://stackoverflow.com/a/1162255
    SoloCompany
        8
    SoloCompany  
       2014-08-13 23:48:40 +08:00
    for : 是语法糖,Iterable 接口和数组生成的bytcode是不同的。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2870 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 15:32 · PVG 23:32 · LAX 08:32 · JFK 11:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.