当前位置: 首页 > 知识库问答 >
问题:

为什么我可以对没有stream()方法的类的对象调用stream()方法?

宗政兴发
2023-03-14

我是大学里的一个新手Java程序员。今天我发现了一些东西,打破了我关于Java语法如何工作的一个概念。

public class testClass {

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

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

在ArrayList类中找不到方法stream(),但它可能看起来好像在那里。当我将鼠标移到Eclipse中的stream()-方法上时,它表示这是集合的一部分,但我在其在线文档中的任何地方都找不到stream()方法。

如果stream()方法不是我调用它的类的一部分,为什么它可以调用它?

共有3个答案

余善
2023-03-14

方法stream()是接口java中定义的默认方法。util。集合。查看java的源代码。util。集合。

它使用java.util.ArrayList上的方法splititerator()来实现。

高正初
2023-03-14

ArrayList实现Collection接口。此接口具有方法stream()

宋鸿
2023-03-14

你检查了正确的类和Java版本吗?Java8的Collection(不是Collection)有一个stream()默认方法,它由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);
}
 类似资料:
  • 当使用Java8流时,获取一个列表、从中创建一个流、处理业务并将其转换回来是很常见的。类似于: 有什么想法吗?

  • 是否可以在使用者中运行方法,如方法引用,但要在传递给使用者的对象上运行: 会是这样的: 但那不起作用... 方法引用是否有可能,或者是-

  • 问题内容: 我不应该能够调用实例化对象的私有方法。我想知道为什么下面的代码有效。 我知道可以从类中访问私有方法。但是,如果类中的方法实例化了同一类的对象,则作用域规则是否不适用于该实例化的对象? 如本例所示,像main这样的静态方法可以访问类的非静态成员吗​​? 问题答案: 您的方法是的方法,因此可以调用的私有方法。 只是因为它是一个方法并不妨碍它表现得像为目的的方法,等等。 只是阻止的方法 等

  • 问题内容: 动物是狗的超类,狗有一种叫bark的方法 考虑以下: 会发生什么? the assignment isn’t allowed the call to bark is allowed and “woof” is printed at run time the call to bark is allowed but nothing is printed the call to bark c

  • 我将得到列表对象的字符串,我想转换为列表对象。有没有办法把那个字符串转换成列表?

  • 问题内容: 以下接口和类已成功编译。 问题在下面的输出中提到: 输出: X 瞧,MyInterface是一个接口, 那为什么编译器允许编译 mi.getClass(),mi.wait()。 或如何在接口中使用Object类的方法。 ÿ 编辑 :-我接受拒绝的答案,因为这是最具解释性的。但是在阅读了答案之后,又出现了一个问题:- “ 请记住,如果接口试图在Object类中声明一个声明为’final’