简体   繁体   English

使用迭代器

[英]Using Iterators

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. Iterator是一个接口,因此要创建一个对象,我们需要创建一个实现Iterator的类,然后为该对象创建一个对象。 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!! 我们怎么会有接口的对象!

Iterator是一个接口,但是map.entrySet().iterator()返回一个实现Iterator接口的对象。

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". 寻找“匿名内部类”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM