实训16 2018.04.16

迭代器

使用迭代器获取集合(Collection)对象:

  

import java.util.*;

public class TestClass {

    public static void main(String[] args){
        Collection<String> collection=new ArrayList<String>();
        collection.add("a");
        collection.add("b");
        
        for(Iterator<String> it=collection.iterator();it.hasNext();)         
               {
            System.out.println(it.next());
        }
    }
}

  当it.hasNext()为false时,使用it.next()会抛出NoSuchElementException异常。

  在Collection中存储时如果不设置泛型,那么默认Object类型对象。当使用其中某个对象的(特有)方法时需要向下转型。

for-each可以对数组和Collection进行遍历,而不需要通过下标。遍历时不能像下标一样进行增删。

至此,有三种迭代集合或数组的方式:

  1. for(int i;i<arr.length;++i){}

  2. for each

  3.for(Iterator<String> it=collection.iterator();it.hasNext();)  {}

泛型 

Java中的泛型是“伪泛型”,不会被保存到.class文件中。泛型类似于一种规范。

  含有泛型的方法:public <T> T[] toArray(T[] a){}

  含有泛型的接口、类:interface Einter<String>{},class Eclass<E>{}。这里使用“E”表示始终不确定泛型的类型,直至被调用时才确定。当然也可以在定义时就给定泛型的类型,像定义的接口那样。

泛型通配符<?> 

public static void printCollection(Collection<?> list) {
    Iterator<?> it = list.iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
}

  使用泛型通配符类似于使用Object,只能使用Obeject类中的方法。

  其中,

    <? extends Parent>表示接收Parent及其子类的对象;

    <? super Children>表示接收Children及其父类(所有父类,直至Object)的对象。

猜你喜欢

转载自www.cnblogs.com/goxxiv/p/8856420.html