For each in java for list interface

Sonali Gupta :

I have the following snippet

class Solution {


    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        int N = rooms.size();
        LinkedList<Integer> adj[] = new LinkedList[N];
        int i=0;
        for(List keys: rooms){
            for(Integer key: keys){
                adj[i].add(key);
                adj[key].add(i); 
            }
            i++;
        }

        return true;
    }
}

I want to iterate using for-each only as I am trying to bring it into practice. I am getting error at the nested for loop saying object cannot be cast into Integer. I am unable to understand why it shouldnt work given rooms is a list of list of Integers. Why does it takes the datatype as Object for elements of keys.

Eng.Fouad :

You forgot the generics argument for List:

for(List keys: rooms)
    ^^^^
for(List<Integer> keys: rooms)

See:

- What is a raw type and why shouldn't we use it?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216274&siteId=1