Java 数组和泛型:Java 等效于 C# IEnumerable<T>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/362367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:50:34  来源:igfitidea点击:

Java Arrays & Generics : Java Equivalent to C# IEnumerable<T>

javaarraysgenerics

提问by Winston Smith

So in C#, I can treat a string[]as an IEnumerable<string>.

因此,在 C# 中,我可以将 astring[]视为IEnumerable<string>.

Is there a Java equivalent?

有Java等价物吗?

采纳答案by Tom Hawtin - tackline

Iterable<String>is the equivalent of IEnumerable<string>.

Iterable<String>相当于IEnumerable<string>

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.

如果实现了数组,这将是类型系统中的一个奇怪现象IterableString[]是 的一个实例Object[],但Iterable<String>不是Iterable<Object>。类和接口不能用不同的泛型参数多次实现相同的泛型接口。

String[]will work just like an Iterablein the enhanced for loop.

String[]将像Iterable在增强的 for 循环中一样工作。

String[]can easily be turned into an Iterable:

String[]可以很容易地变成Iterable

Iterable<String> strs = java.util.Arrays.asList(strArray);

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 1.5 开始就很少需要了。

回答by Learning

Iterable <T>

Iterable <T>

回答by bruno conde

Are you looking for Iterable<String>?

你在找Iterable<String>吗?

Iterable<T> <=> IEnumerable<T>
Iterator<T> <=> IEnumerator<T>

回答by Dan Vinton

I believe the Java equivalent is Iterable<String>. Although String[]doesn't implement it, you can loop over the elements anyway:

我相信 Java 的等价物是Iterable<String>. 虽然String[]没有实现它,但你可以循环遍历元素:

String[] strings = new String[]{"this", "that"};
for (String s : strings) {
    // do something
}

If you really need something that implements Iterable<String>, you can do this:

如果你真的需要实现的东西Iterable<String>,你可以这样做:

String[] strings = new String[]{"this", "that"};
Iterable<String> stringIterable = Arrays.asList(strings);

回答by slavpetroff

Iterable<T>is OK, but there is a small problem. It cannot be used easily in stream()i.e lambda expressions.

Iterable<T>可以,但是有一个小问题。它不能在stream()ie lambda 表达式中轻松使用。

If you want so, you should get it's spliterator, and use the class StreamSupport().

如果你愿意,你应该得到它的 spliterator,并使用 class StreamSupport()