Reputation: 743
I have the following code:
for (Map.Entry < Integer, ArrayList < String >> entry: data.entrySet()) {
Integer key = entry.getKey();
ArrayList < String > value = entry.getValue();
for (String aString: value) {
System.out.println("key : " + key + " value : " + aString);
}
}
Hashmap is declared as
Map<Integer, List<String>> data = new HashMap<>();
before filling it via a loop and put
methods.
I now need to iterate the ArrayList
of strings or better, retrieve specific elements by index .. for manipulation. I have researched as far as I can and seemed to have found the answer, with the above code. It was copied from an answer given here some time back.
However, when I try to use it complains of "Incompatible Types" with the top line underlined in red up to the colon.
Entry <Integer,java.util.List<java.lang.String>>
Entry <Integer,java.util.ArrayList<java.lang.String>>
Upvotes: 1
Views: 70
Reputation: 44398
Program against the interface rather than against an implementation.
The Map's type is Integer
as a key and List<String>
as a value. Thus you can loop the entries only with the very same structure.
for (Map.Entry < Integer, List < String >> entry: data.entrySet()) {
Integer key = entry.getKey();
List <String> value = entry.getValue();
for (String aString: value) {
System.out.println("key : " + key + " value : " + aString);
}
}
Upvotes: 0
Reputation: 9786
In your case you have the List
interface and the ArrayList
implementation, you have correctly used the List
type in the declaration of the map, but you passed to declaring a implementaion (ArrayList
) in the loop.
The problem arrises because of the statement:
Map<Integer, List<String>> data = new HashMap<>();
The empty diamond notation leaves open many options for a implementation of the List<String>
. It can be ArrayList, LinkedList etc. So you can't be sure that the compiler will use ArrayList
implementation.
To favour code extendibility is advisable to do what is known as programming against interfaces. It is always good to maintain the most generic type as long as you can to avoid coupling your code to a specific implementation, that is you will specifiy the implementation when you need to perform some concrete operation on it.
Upvotes: 1
Reputation: 39
Try below code:
for (Map.Entry<Integer, List<String>> entry : data.entrySet()) {
Integer key = entry.getKey();
List<String> value = entry.getValue();
for(String aString : value){
System.out.println("key : " + key + " value : " + aString);
}
Upvotes: 0
Reputation: 1038
because you have declared value type in Hashmap
as List<String>
and you have given ArrayList<String>
as value type Map.Entry
in for loop
.
change Map<Integer, List<String>> data = new HashMap<>();
to Map<Integer, ArrayList<String>> data = new HashMap<>();
Upvotes: 1