Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare the ArrayList in this way?

Tags:

java

arraylist

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?

like image 212
tonyabracadabra Avatar asked Jul 22 '15 09:07

tonyabracadabra


People also ask

How do you declare ArrayList?

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.

Can we declare ArrayList size?

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.

How do you declare an ArrayList in Java?

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.

Can we declare ArrayList as static in Java?

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.


1 Answers

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).

like image 162
Tim Biegeleisen Avatar answered Sep 21 '22 18:09

Tim Biegeleisen