问题描述
因此在 C# 中,我可以将 string[]
视为 IEnumerable
.
So in C#, I can treat a string[]
as an IEnumerable<string>
.
是否有 Java 等价物?
Is there a Java equivalent?
推荐答案
Iterable
等价于 IEnumerable
.
如果数组实现了Iterable
,这将是类型系统的一个奇怪之处.String[]
是 Object[]
的实例,但 Iterable
不是 Iterable
>.类和接口不能用不同的泛型参数多次实现相同的泛型接口.
It would be an odditity in the type system if arrays implemented Iterable
. String[]
is an instance of Object[]
, but Iterable<String>
is not an Iterable<Object>
. Classes and interfaces cannot multiply implement the same generic interface with different generic arguments.
String[]
将像增强的 for 循环中的 Iterable
一样工作.
String[]
will work just like an Iterable
in the enhanced for loop.
String[]
可以很容易地变成一个 Iterable
:
String[]
can easily be turned into an Iterable
:
Iterable<String> strs = java.util.Arrays.asList(strArray);
更喜欢集合而不是数组(无论如何对于非原语).引用类型的数组有点奇怪,从 Java 1.5 开始就很少需要了.
Prefer collections over arrays (for non-primitives anyway). Arrays of reference types are a bit odd, and are rarely needed since Java 1.5.
这篇关于Java 数组 &泛型:Java 等效于 C# IEnumerable<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!