-3

The basic difference between the set and the list is that set wont allow the duplicates the question is why cant we use original for loop for the set as we use for list

eg: length of set and list is same

   for(int i =0 ; i< list.size;i++){
    list.get(i);
    set.get(i);  // here it is throwing an error like get(index ) cant be applied for set

}

but if i use advance for loop(for each) its working

for(Object sample : set){
 system.out.println(sample);

}

why is this happening ... is there any operational defference between for loop and for each , set and list ....

any help and suggestion would be useful ... thank you in advance

  • 1
    A set has no `get()` method. You should check the docs https://docs.oracle.com/javase/7/docs/api/java/util/Set.html – forgivenson May 26 '16 at 12:18

1 Answers1

6

A Set doesn't have an order, and therefore it doesn't have a get(index) method. Therefore you can't call set.get(i).

The enhanced for loop, on the other hand, works with any class that implements Iterable (as well as with arrays), which includes any Collection. For Sets it will iterate over the elements in an order that depends on the specific Set implementation.

Eran
  • 387,369
  • 54
  • 702
  • 768