代码之家  ›  专栏  ›  技术社区  ›  dfa

为什么数组不能分配给Iterable?

  •  195
  • dfa  · 技术社区  · 17 年前

    Foo[] foos = ...
    for (Foo foo : foos) 
    

    或者只是在for循环中使用Iterable。这很方便。

    public void bar(Iterable<Foo> foos) { .. }
    

    并用数组调用它,因为它不是Iterable:

    Foo[] foos = { .. };
    bar(foos);  // compile time error 
    

    5 回复  |  直到 16 年前
        1
  •  67
  •   Gray droiddeveloper    9 年前

    数组可以实现接口( Cloneable java.io.Serializable Iterable ?我猜 可迭代 力量添加 iterator char[] 甚至不会覆盖 toString List Arrays.asList 将显式地为您进行转换。

    clone 在数组上。)

        2
  •  55
  •   Gareth Adamson    16 年前

    数组是一个Object,但它的项可能不是。数组可能包含像int这样的基本类型,Iterable无法处理。至少我是这么想的。

        3
  •  16
  •   Daniel Earwicker    12 年前

    数组应该支持 Iterable 出于同样的原因,他们就是不这样做。NET数组不支持允许按位置进行只读随机访问的接口(没有这样的标准接口)。基本上,框架中经常有恼人的小漏洞,不值得任何人花时间来修复。如果我们能以某种最佳方式自己修复它们也没关系,但通常我们做不到。

    为了公平起见,我提到了。NET数组不支持按位置随机访问的接口(另见我的评论)。但是在。NET 4.5,已经定义了确切的接口,并且由数组和 List<T>

    IReadOnlyList<int> a = new[] {1, 2, 3, 4};
    IReadOnlyList<int> b = new List<int> { 1, 2, 3, 4 };
    

    由于可变列表接口的存在,一切仍然不太完美 IList<T> 不继承 IReadOnlyList<T> :

    IList<int> c = new List<int> { 1, 2, 3, 4 };
    IReadOnlyList<int> d = c; // error
    

    如果新版本的Java在类似方面有任何进展,我很想在评论中知道! :)

        4
  •  14
  •   dlamblin    9 年前

    不幸的是,数组不是 class -够了”。他们没有实施 Iterable

    数组不是正常意义上的对象

    您可以在每个循环中使用它们的原因是Sun为数组添加了一些语法糖(这是一个特例)。

    由于在Java 1中数组最初是“几乎对象”,因此对其进行更改将过于剧烈 Java中的对象。