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?
Declaring and Creating ArrayLists. To declare a ArrayList use ArrayList<Type> name Change the Type to be whatever type of objects you want to store in the ArrayList, for example String as shown in the code below.
ArrayList class is a resizable array, present in java. util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array.
The general syntax of this method is:ArrayList<data_type> list_name = new ArrayList<>(); For Example, you can create a generic ArrayList of type String using the following statement. ArrayList<String> arraylist = new ArrayList<>(); This will create an empty ArrayList named 'arraylist' of type String.
This is the older, pre-Java 9 approach I used to use to create a static List in Java (ArrayList, LinkedList): static final List<Integer> nums = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; As you can guess, that code creates and populates a static List of integers.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With