-1

I am intrigued by something that looks obvoius, but it's not for me. We have a hashSet and Iterator:

Set<String> set = new HashSet<>();
Iterator it = set.iterator();

I know, how iterator works, but there's something weird to me:

Iterator* it = set.iterator();**
* ok, wait. Iterator is an interface, not a class. So... ?
** ok, set is an object of class HashSet, and it implements interface Iterator, so ith has void interator() imlemented, nothing unusual.

But how can we create Iterator object from Iterator interface ?

RichardK
  • 3,228
  • 5
  • 32
  • 52

2 Answers2

5

The implementation of iterator() method in HashSet returns an object that implements the Iterator interface. The object returned is an instance of some concrete class that conforms to the Iterator specification.

http://en.wikipedia.org/wiki/Polymorphism_(computer_science)

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Thanks, but how can we make Iterator it = ... We can make String, Integer - objects, but not interfaces. – RichardK Oct 21 '14 at 20:36
  • `HashMap` returns an object of a concrete class implementing `Iterator`, however said class is hidden and/or anonymous. The 'user' of `.iterator()` shouldn't care either way. – Mark Jeronimus Oct 21 '14 at 20:37
  • FYI, found the class here: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java#HashMap.KeyIterator – Mark Jeronimus Oct 21 '14 at 20:41
5

First of all, HashSet implements Iterable and not Iterator. The two interfaces are related but distinct.

Now to your question. All that

Iterator it = ...;

really means is that it is a reference to an instance of a class implementing the Iterator interface. It's not a reference "to an interface" (such a thing would indeed not make a lot of sense since you can't instantiate an interface).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Thanks! I tried to make a test - something that makes no sense, but it works: Comparable test = String.valueOf(1); – RichardK Oct 21 '14 at 20:39
  • @RichardK: `String.valueOf(1)` returns an instance of a class implementing the `Comparable` interface. – NPE Oct 21 '14 at 20:40
  • Yes, i tried to make something similar to my question, just to test if complilator or JVM will take as exception. It works. – RichardK Oct 21 '14 at 20:42