0

I have a very basic question in mind. An Iterator is an interface so to create an object we will need to create a class that implements Iterator and then create an object for the same. But when i saw the use of iterator it confused me as we are referencing an interface directly without having a class that implements it. for example :

HashMap map = new HashMap();
   map.put("1", "One");
   map.put("2", "Two");
   Iterator i = map.entrySet().iterator();

how come we have an object of an Interface!!

4
  • And what about: Map map = new HashMap();? Commented May 14, 2012 at 11:04
  • @AlexStybaev it will get you a new HashMap instance that can be accessed like any Map. Commented May 14, 2012 at 11:06
  • @DerMike i know it. That is just the same as for Iterator, isn't it? Just an implementation of Iterator interface. Commented May 14, 2012 at 11:09
  • 2
    I think the problem is that @Amit doesn't see class which implements Iterator returned by iterator method. This class is inner class in HashMap and is not public. Here it is. Commented May 14, 2012 at 11:11

2 Answers 2

5

Iterator is a interface, but map.entrySet().iterator() returns an object which implements the Iterator interface.

Sign up to request clarification or add additional context in comments.

1 Comment

To add: here is real class which used by HashMap. grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/…
0

You'll get some implementation from that call. You just cannot assume more than the things that are enforced (and documented) be the iterator interface. Look for "anonymous inner class".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.