迭代<?> vs java中的Iterator [英] Iterator<?> vs Iterator in java
问题描述
可能重复:
什么是原始类型,为什么我们不应该使用它?
这个问题几乎完全包含在描述中:
The question is pretty much self contained in the description: what is the difference between
Iterator<?>
和
Iterator
java中的对象?它们都在对象类型上进行迭代吗?
objects in java? They both iterate over Object types right?
推荐答案
不。 Iterator<?>
迭代?
s(某种类型派生自 Object
),而 Iterator
仅提供对象
。这是Java中的泛型支持。
Nope. Iterator<?>
iterates over ?
s (some type that derives from Object
), while Iterator
only provides Object
s. This is the generics support in Java.
什么是?
类型?嗯,这是一个很好的问题。
What's a ?
type? Well, that's a great question.
回到Java 5之前的旧时代,你有无类型的集合和无类型的迭代器。所以你的集合中有 Object
s,你必须手动投射它们。例如:
Back in the bad old days before Java 5, you had untyped collections and untyped iterators. So you'd have Object
s in your collections and you'd have to cast them manually. For example:
List foo = new ArrayList();
foo.add("Foo!");
for(Iterator i = foo.iterator(); i.hasNext(); )
{
Object element = i.next();
System.out.println((String)element);
}
请注意演员表?那是因为我们只是将 Object
填入列表中,我们必须自己做所有的内务处理。仅仅列表
就不那么糟了,但想象一下包含地图的地图,其中包含一个包含......的地图,你明白了。你正在施展地狱,你很快就不知道你是否正在查看从 String
到整数$ c的地图$ c>或您的其他地图从
Integer
向后转移到 String
。
Notice that cast? That's because we're just stuffing Object
s into lists, and we have to do all that housekeeping ourselves. Not so bad with just a List
, but imagine a map that contains a map that contains a map that contains a ... well, you get the idea. You're in casting hell and you can pretty quickly not know whether you're looking at a map that goes from String
to Integer
or your other map that goes backwards from Integer
to String
.
在Java 5中,你可以使用泛型,所以现在你可以说:
In Java 5, you can use generics, so now you can say:
List<String> foo = new ArrayList();
foo.add("Foo!");
for(Iterator<String> i = foo.iterator(); i.hasNext(); )
{
String element = i.next();
System.out.println(element);
}
请注意,演员表是不必要的?当我们使用 List< String>
时,我们可以使用 Iterator< String>
并具有一些类型安全性。
Note that the cast was unnecessary? When we use a List<String>
, we can use an Iterator<String>
and have some type safety.
当您开始处理更复杂的数据结构时,这非常有用,例如:
This is really beneficial when you start doing things with more complex data structures, like:
Map<String, Map<String, Map<String, SomeRandomObject>>> complexMap;
这篇关于迭代<?> vs java中的Iterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!