void topologicalSortUtil(int v, boolean visited[], Stack<Integer> stack, ArrayList<Integer>[] adj) {
visited[v] = true;
for (int i : adj[v]) {
if (!visited[i]) {
topologicalSortUtil(i, visited, stack, adj);
}
}
stack.push(v);
}
Here, I am calling an array of arraylist. The error is in the enhanced for loop, as told by my IDE (IntelliJ). It seems like a perfectly valid call as adj[v] would return an ArrayList and the integer i catching each elements of the array as they come and then processing them in the recursive call.
@Alex Shesterov and others, Here is the code using which adj was generated.
ArrayList[] arr = new ArrayList[n+1];
for(int i=0; i<=n; i++){
arr[i] = new ArrayList<Integer>();
}
arr[1].add(Arrays.asList(8,6,2));
arr[2].add(Arrays.asList(7));
arr[3].add(Arrays.asList(6));
arr[4].add(Arrays.asList(5,2));
arr[5].add(Arrays.asList(4,2,3));
arr[6].add(Arrays.asList(3,2,5));
arr[7].add(Arrays.asList(2));
arr[7].add(Arrays.asList(1,2,4));
The code in which you generate the array is incorrect and type-unsafe. You are probably getting warnings about "unsafe types" or "raw types" from the compiler. The following is a use of a raw type:
ArrayList[] arr = new ArrayList[n+1];
You should never use the type ArrayList
without some kind of type declaration.
You then initialize each of the elements of arr
to be an ArrayList<Integer>
. But since this is assigned to a raw typed array element, the compiler doesn't know that the element is an ArrayList<Integer>
and doesn't warn you about your next step, which is the bad one:
arr[1].add(Arrays.asList(8,6,2));
You add an element to the list in arr[1]
. The add
method adds a single element, which is the object that is passed to it. And what is that object? It's a List
, which is produced by Arrays.asList(...)
.
So instead of having an ArrayList<Integer>
you have a raw ArrayList
which has a single element, and that element is a list of integer. And this, of course, cannot be cast to Integer
.
Instead of using add
you should have used addAll
. The addAll
method adds all the elements in the collection it receives to the collection on which it is called.
arr[1].addAll(Arrays.asList(8,6,2));
It would have been better not to mix arrays and lists, but to pass a list of lists and give it the appropriate type.
Try to avoid raw types and eliminate all raw type or unsafe type warnings from your code (not by @SupressWarnings
!), unless you start programming libraries for generic collections and you know what you are doing.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments