Why can I call the stream() method on objects of a class that don't have the stream()-method?

扶醉桌前 提交于 2019-12-12 01:26:47

问题


I'm a novice Java programmer at university. I discovered something today that broke one of my conceptions about how Java syntax works.

public class testClass {

ArrayList <String> persons = new ArrayList <String> ();

public void run(){
    Stream <String> personstream = persons.stream();
}}

The method stream() is not found in the ArrayList class, yet it might appear as if it's there. When I move my mouse over the stream()-method in Eclipse, it says it's part of Collections, but I don't find the stream() method anywhere in its online documentation.

Why does it work to call the stream() method if it's not part of the class I'm calling it from?


回答1:


Did you check the right class and Java version? Java 8's Collection (not Collections) has a stream() default method, which is inherited by ArrayList:

/**
 * Returns a sequential {@code Stream} with this collection as its source.
 *
 * <p>This method should be overridden when the {@link #spliterator()}
 * method cannot return a spliterator that is {@code IMMUTABLE},
 * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
 * for details.)
 *
 * @implSpec
 * The default implementation creates a sequential {@code Stream} from the
 * collection's {@code Spliterator}.
 *
 * @return a sequential {@code Stream} over the elements in this collection
 * @since 1.8
 */
default Stream<E> stream() {
    return StreamSupport.stream(spliterator(), false);
}



回答2:


ArrayList implements the Collection interface. This interface has the method stream()




回答3:


The method stream() is a default method defines in the interface java.util.Collection. Look at the source of java.util.Collection.

It uses the method splititerator() on java.util.ArrayList for the implementation.




回答4:


This is valid Java 8 code:

List<String> persons = new ArrayList<>();
Stream<String> stream = persons.stream();

List<T>.stream() is available.



来源:https://stackoverflow.com/questions/30343726/why-can-i-call-the-stream-method-on-objects-of-a-class-that-dont-have-the-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!