gpt4 book ai didi

java - 我可以用这种方式声明 ArrayList 吗?

转载 作者:搜寻专家 更新时间:2023-10-30 19:50:14 25 4
gpt4 key购买 nike

Iterable<Board> theNeighbors = new ArrayList<Board>();

这是我对 ArrayList theNeighbors 的初始化,它使用接口(interface) Iterable 进行声明。但是,当我对刚刚构建的变量使用方法 add() 时,编译器会发出警报

Board.java:78: error: cannot find symbol theNeighbors.add(nb); ^
symbol: method add(Board)
location: variable theNeighbors of type Iterable

是什么让它发生?在另一种情况下,当我使用

List<Board> theNeighbors = new ArrayList<Board>();

add() 方法效果很好。你为声明选择的接口(interface)是否应该总是有你以后要调用的方法?

最佳答案

如果您阅读 documentation对于 Iterable 接口(interface),正如您提到的,您将看到 add() 方法不存在。

Is it true that the interface you choose for the declaration should always have the method you want to call later?

您选择的接口(interface)应该具有您计划实例化和使用的对象的所有行为。

当你像这样声明你的ArrayList时:

Iterable<Board> theNeighbors = new ArrayList<Board>();

JVM 将 theNeighbors 视为 Iterable,因此无法找到 add() 方法。另一方面,如果您这样定义 ArrayList:

List<Board> theNeighbors = new ArrayList<Board>();

然后 JVM 可以找到一个 add() 方法,因为所有类型的 List 都有这个方法(和行为)。

关于java - 我可以用这种方式声明 ArrayList 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31558584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com