tonyabracadabra tonyabracadabra - 5 months ago 9
Java Question

Can I declare the ArrayList in this way?

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


Here is my initialization for the
ArrayList
theNeighbors, which uses the interafce
Iterable
for declaration. However, as I use method
add()
to the variable I just built, the compiler alerts


Board.java:78: error: cannot find symbol theNeighbors.add(nb);
^

symbol: method add(Board)

location: variable theNeighbors of type Iterable


What makes it happen? In another case while I use

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


The
add()
method works well. Is it true that the interface you choose for the declaration should always have the method you want to call later?

Answer

If you read the documentation for the Iterable interface, you will see, as you mentioned, that the add() method does not exist.

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

The interface you choose should have all the behaviors of the object you plan to instantiate and use.

When you declare your ArrayList like this:

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

the JVM treats theNeighbors as an Iterable and therefore cannot find the add() method. On the other hand, if you define your ArrayList this way:

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

then the JVM can find an add() method since all types of List have this method (and behavior).

Comments