-1

I have a problem in my mind, why i can't get an element from Set by using normal For Loop, but when i use Enhanced For Loop all things work normal. Example :

private static Set<HeavenlyBody> planets = new HashSet<>();

for (HeavenlyBody getPlanet : planets){
     System.out.println("\t"+getPlanet.getName()+": "+getPlanet.getOrbitalPeriod());
}

How getPplanet object in Enhanced For Loop can get the element if Set doesn't have that technique? and how can i do it by normal For Loop? Best Regards

Abdelillah
  • 79
  • 1
  • 14

1 Answers1

2

The brief answer is: The Set implements Iterable, it is why its possible to iterate via elements with for loop

The NORMAL for loop doesn't work, because Set doesn't have get() method. And the reason why it is ommited, is in datastructure onto Set is built

Alex Faster
  • 199
  • 10