HashSet initialized in Java

advertisements

I'm having a problem initializing array of HashSet

  int N = 100;
  HashSet<Integer> []array = new HashSet[N];
  for (HashSet<Integer> set:array){
    set = new HashSet<Integer>();
  }

But the array contains only null. (Also error when HashSet []array = .... )

But when running with:

   for(int i = 0; i < N; i++){
      array[i] = new HashSet<Integer>();
   }

All is well.

Why does the first code isn't working? Is it my mistake?

Thank you


You never actually assign initialized instances to elements of the array. Instead you iterate over the elements of the array with a variable that gets assigned to a new object in your loop, then is never used. In a case like this the enhanced for...each syntax is not appropriate, use the traditional for loop instead.