andybest
V2EX  ›  问与答

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

  •  
  •   andybest · Aug 13, 2014 · 2472 views
    This topic created in 4310 days ago, the information mentioned may be changed or developed.
    比如 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 replies    2014-08-13 23:48:40 +08:00
    vainly
        1
    vainly  
       Aug 13, 2014
    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  
       Aug 13, 2014
    cxe2v
        3
    cxe2v  
       Aug 13, 2014
    我只晓得在C#里有个IEnumrable接口可以代表这两个类型
    andybest
        4
    andybest  
    OP
       Aug 13, 2014
    @Mutoo 数组怎么实现 Iterable ?
    Mutoo
        5
    Mutoo  
       Aug 13, 2014
    @andybest 数组本身就是 Iterable 的,你只要用

    public void process(Iterable<Deal> deals)

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

    http://stackoverflow.com/a/1162255
    SoloCompany
        8
    SoloCompany  
       Aug 13, 2014
    for : 是语法糖,Iterable 接口和数组生成的bytcode是不同的。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1699 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 5414617a · 39ms · UTC 16:19 · PVG 00:19 · LAX 09:19 · JFK 12:19
    ♥ Do have faith in what you're doing.