简体   繁体   中英

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

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?

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);
}

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

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.

This is valid Java 8 code:

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

List<T>.stream() is available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM