【发布时间】:2016-04-09 18:38:42
【问题描述】:
我想知道是否有办法检查迭代器对象。是一种地图吗?
另外,有没有更好的方法来获取迭代器对象的内容并将它们放入 mapC 中?
这是我的代码:
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;
import java.util.Iterator;
public class Maps {
public static void main(String[] args) {
Map mapA = new HashMap();
Map mapB = new TreeMap();
mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");
// The three put() calls maps a string value to a string key. You can then
// obtain the value using the key. To do that you use the get() method like this:
String element1 = (String) mapA.get("key1");
// why do I need the type cast on the right?
System.out.println(element1);
// Lets iterate through the keys of this map:
Iterator iterator = mapA.keySet().iterator();
System.out.println(iterator); // How to inspect this? Is it a kind of map?
Map mapC = new HashMap();
while(iterator.hasNext()){
Object key = iterator.next();
Object value = mapA.get(key);
mapC.put(key,value);
} // Is there a better way to take the contents of the iterator and put them in a new map?
System.out.println(mapC);
}
}
【问题讨论】:
-
你说的inspect是什么意思?
Iterator是Iterator。iterator()方法返回的实际对象是实现了Iterator的类型。 -
您想通过检查迭代器了解什么?
-
旁注:不要使用原始类型。
-
System.out.println(iterator.getClass()); -
一般 - 不要“检查”它 - 使用接口方法
hasNext和next来获取值。有大量不同的迭代器实现(我的工作区中有 100 多个)
标签: java