I thought [] brackets can only be used in normal arrays until I came across this answer below,
class Solution {
Set<Integer> seen = new HashSet();
int MAX_EDGE_VAL = 1000;
public int[] findRedundantConnection(int[][] edges) {
ArrayList<Integer>[] graph = new ArrayList[MAX_EDGE_VAL + 1]; //Normally I've seen This line without [] brackets. But How [] brackets here impacts the list. What are the things we can do to a list if [] brackets are added at declaraton.
for (int i = 0; i <= MAX_EDGE_VAL; i++) {
graph[i] = new ArrayList(); //Also Here they are assigning a list like we do in an array. Also my another doubt is graph list accepts only Integer values but here they are assigning new list to each element of graph list instead of integer which they have specified during declaration
}
for (int[] edge: edges) {
seen.clear();
if (!graph[edge[0]].isEmpty() && !graph[edge[1]].isEmpty() &&
dfs(graph, edge[0], edge[1])) {
return edge;
}
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
throw new AssertionError();
}
public boolean dfs(ArrayList<Integer>[] graph, int source, int target) {
if (!seen.contains(source)) {
seen.add(source);
if (source == target) return true;
for (int nei: graph[source]) {
if (dfs(graph, nei, target)) return true;
}
}
return false;
}
}
If you find confusing looking at the full code, Here is the part where my doubt arises,
ArrayList<Integer>[] graph = new ArrayList[MAX_EDGE_VAL + 1]; //Normally I've seen This line without [] brackets.
//But How [] brackets here impacts the list. What are the things we can do to a list if [] brackets are added at declaraton.
for (int i = 0; i <= MAX_EDGE_VAL; i++) {
graph[i] = new ArrayList(); //Also Here they are assigning a list like we do in an array.
//Also my another doubt is graph list accepts only Integer values but here they are assigning new list to each element of graph list instead of integer which they have specified during declaration
}
My Doubt is included in the above code as comments.
>` ... ??
– MadProgrammer Aug 30 '20 at 05:14>`, which is basically the same as `List[]` ... just allows for a more dynamic workflow
– MadProgrammer Aug 30 '20 at 06:52