Reputation: 3283
What on earth could be causing this? I'm getting two contradicting errors on one method I'm trying to create in a java program
public void numberOfTrianglesIncidentToVertex(){
for(List<Integer> pairs: neighbors.get(2)){ // Type mismatch: cannot convert from element type Integer to List<Integer>
}
int fail = neighbors.get(2); // Type mismatch: cannot convert from List<Integer> to int
}
The neighbors variable is declared in a super class as follows:
List<List<Integer>> neighbors
= new ArrayList<List<Integer>>();
I don't know why it would tell me on one line that its an Integer and can't be converted to a List of integers and then on the very next line just change its mind and say the exact opposite. which is it?
Upvotes: 1
Views: 147
Reputation: 8928
neighbors.get(2)
returns you List<Integer>
. Second warning is clear about that.
Type mismatch: cannot convert from element type Integer to List
To iterate over this list you'll need to iterate over i - integer.
for(Integer pairs: neighbors.get(2))
Upvotes: 1
Reputation: 213223
Given your declaration of neighbors, the following invocation:
neighbors.get(2);
will give you a List<Integer>
.
Now in 1st snippet, you are trying to iterate over the return value. So, when you iterate over List<Integer>
, you get back values of type Integer
. And you are using List<Integer>
type loop variable. Hence that error message. You can't assign an Integer
reference to a List<Integer>
reference.
You should change your loop to:
for(int val: neighbors.get(2)) { // 'int' works in place of 'Integer', due to unboxing
}
However, if you iterate on neighbors
, your loop will work fine, because then you will get List<Integer>
reference on iterating.
for(List<Integer> val: neighbors) {
}
In 2nd snippet, you are directly assigning the fetched value - List<Integer>
to an int
primitive. Which obviously you can't do. They aren't at all compatible. Hence the error message.
The assignment should be like:
List<Integer> list = neighbors.get(2);
Upvotes: 5