黑马程序员技术交流社区

标题: 遍历集合时Iterator与Iterator<?> 都可以接受任意类型集合,那... [打印本页]

作者: noiary    时间: 2014-9-25 20:39
标题: 遍历集合时Iterator与Iterator<?> 都可以接受任意类型集合,那...
  1. /*
  2. 遍历集合时Iterator与Iterator<?> 都可以接受任意类型集合,那么写与不写 "<?>" 有什么区别呢?
  3. 例:
  4. */
  5. import java.util.*;
  6. /*
  7. GenericTest
  8. */

  9. public class GenericTest {

  10.         public static void main(String[] args) {
  11.        
  12.                 ArrayList<String> al1 = new ArrayList<String>();
  13.                 al1.add("abc01");
  14.                 al1.add("abc02");
  15.                 al1.add("abc03");
  16.                
  17.                 ArrayList<Integer> al2 = new ArrayList<Integer>();
  18.                 al2.add(4);               
  19.                 al2.add(5);               
  20.                 al2.add(2);
  21.                
  22.                 printAl(al1);
  23.                 printAl(al2);
  24.         }
  25.        
  26.         public static void printAl(ArrayList/*<?>*/ al) {
  27.        
  28.                 //for(Iterator<?> it = al.iterator(); it.hasNext(); )
  29.                 for(Iterator it = al.iterator(); it.hasNext(); )
  30.                         System.out.println(it.next());
  31.         }       
  32. }
复制代码





作者: Nullifier    时间: 2014-9-25 20:48
没区别吧
作者: noiary    时间: 2014-9-25 23:15
Nullifier 发表于 2014-9-25 20:48
没区别吧

{:3_49:}  不会吧...


后来试了下集合内装入自定义类,Iterator如果不加<对象类型>得进行强转,加<?>的话找不到具体方法(al.next().getName())    继续迷茫中
作者: 苏乞儿    时间: 2014-9-25 23:35
写上泛型,主要是告诉迭代器取得是什么啊,,这样后边的就不用强转了啊,要是不加,迭代器默认取得是Object,就得强转了,,这有什么难理解的吗?
作者: 苏乞儿    时间: 2014-9-25 23:36
noiary 发表于 2014-9-25 23:15
不会吧...

找不到具体的方法?楼主自定义类中写了getName()方法了吗?
作者: noiary    时间: 2014-9-25 23:38
苏乞儿 发表于 2014-9-25 23:36
找不到具体的方法?楼主自定义类中写了getName()方法了吗?

恩恩 这个我明白了..

只是不清楚在迭代器中加 <?>  与不加有什么区别..
作者: 苏乞儿    时间: 2014-9-25 23:42
noiary 发表于 2014-9-25 23:38
恩恩 这个我明白了..

只是不清楚在迭代器中加   与不加有什么区别..

如果集合上不加泛型,就都不加。如果集合上加了,迭代器必须加。因为你在添加元素的时候add方法默认添加的是Object,所以取出的时候,就必须加强转,但是加了泛型之后,迭代器就能从头到尾的知道自己取得是什么对象了,所以就不用再强转了,这也是泛型的作用之一。。如果不理解,楼主可以用高级for遍历。。
作者: 黑马童宇    时间: 2014-9-26 00:02
这样是为了安全,举个例子
ArrayList<Student> a1 = new ArrayList<Student>();
a1集合装的都应该是Student对象,而在装其他类型的对象




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2