为集合设置通用类型
可以为Java Collections API中的大多数组件指定通用类型
为Java集合设置通用类型时,需要在声明引用它的变量时进行设置
Collection<String> stringCollection=new HashSet<>();
现在,此stringCollection只能包含String实例。 如果您尝试添加其他任何内容,或将集合中的元素强制转换为String以外的任何其他类型,则编译器会报错
You can specify a generic type for a List’s, Set’s etc.
Generic iterator
为Java集合指定通用类型后,该通用类型也适用于iterator()方法返回的Iterator。 这是一个如何获取设置了通用类型的Iterator的示例:
Collection<String> stringCollection = new HashSet<>();
stringCollection.add("eason");
stringCollection.add("vae");
stringCollection.add("Trump");
Iterator<String> iterator = stringCollection.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
it is not necessary to cast the String returned from the iterator.next() method call. Because the Iterator has its generic type set to String, the Java compiler already knows that next() will return a String.
Generic Iteration Using for Loop
Collection<String> stringCollection = new HashSet<>();
stringCollection.add("eason");
stringCollection.add("vae");
stringCollection.add("Trump");
for (String element : stringCollection) {
System.out.println(element);
}
Notice how it is possible to specify the type of the variable of each element (stringElement) as String. This is possible because the generic type of the Collection is set to String.