java collection和Iterator

   Collection是描述所有 序列容器的共性的根接口,它可以被认为是一个"附属接口",即因为要表示其他若干个接口的共性而出现的接口,另外,java.uitl.AbstaractCollection类提供了Collection的默认实现,使得你可以创建AbstractCollection的子类型,而其中没有不必要的重复

  使用接口描述的一个理由是它可以使我们能够创建更通用的代码,通过针对接口而非具体实现来编写代码,我们的代码可以应用于任何实现了Collection的类--这也就使得一个新类可以选择去实现Collection接口,以便我们可以使用它

package object;
//: holding/InterfaceVsIterator.java
import typeinfo.pets.*;
import java.util.*;

public class InterfaceVsIterator {
  public static void display(Iterator<Pet> it) {
    while(it.hasNext()) {
      Pet p = it.next();
      System.out.print(p.id() + ":" + p + " ");
    }
    System.out.println();
  }
  public static void display(Collection<Pet> pets) {
    for(Pet p : pets)
      System.out.print(p.id() + ":" + p + " ");
    System.out.println();
  }    
  public static void main(String[] args) {
    List<Pet> petList = Pets.arrayList(8);
    Set<Pet> petSet = new HashSet<Pet>(petList);
    Map<String,Pet> petMap =
      new LinkedHashMap<String,Pet>();
    String[] names = ("Ralph, Eric, Robin, Lacey, " +
      "Britney, Sam, Spot, Fluffy").split(", ");
    for(int i = 0; i < names.length; i++)
      petMap.put(names[i], petList.get(i));
    display(petList);
    display(petSet);
    display(petList.iterator());
    display(petSet.iterator());
    System.out.println(petMap);
    System.out.println(petMap.keySet());
    display(petMap.values());
    display(petMap.values().iterator());
  }    
} /* Output:
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat
{Ralph=Rat, Eric=Manx, Robin=Cymric, Lacey=Mutt, Britney=Pug, Sam=Cymric, Spot=Pug, Fluffy=Manx}
[Ralph, Eric, Robin, Lacey, Britney, Sam, Spot, Fluffy]
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
*///:~

   当你要实现一个不是Collection的外部类时,由于让它去实现Collection接口可能非常困难,因此使用Iterator就会变得非常吸引人,实现Collection就必须实现iterator(),并且只拿iterator()与继承AbstaractCollection相比花费的代价略微减小

package object;
//: holding/CollectionSequence.java
import typeinfo.pets.*;
import java.util.*;

public class CollectionSequence
extends AbstractCollection<Pet> {
  private Pet[] pets = Pets.createArray(8);
  public int size() { return pets.length; }
  public Iterator<Pet> iterator() {
      return new Iterator<Pet>() {
          private int index = 0;
          public boolean hasNext() {
            return index < pets.length;
          }
          public Pet next() { return pets[index++]; }
          public void remove() { // Not implemented //remove()方法时一个可选操作,可以不实现
            throw new UnsupportedOperationException();
          }
        };
      }    
  public static void main(String[] args) {
    CollectionSequence c = new CollectionSequence();
    InterfaceVsIterator.display(c);//ColectionSequence通过继承抽象Collection实现了功能
    InterfaceVsIterator.display(c.iterator());
  }
} /* Output:
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
*///:~

   如果你的类已经继承类其他的类,那么你就不能再继承AbstractCollection了,再这种情况下,要实现Collection就必须实现该接口中的所有方法,此时,继承并提供创建迭代器的能力就会显得容易的多了,生成Iterator是将队列与消费队列的方法连接再一起耦合度最小的方式,并且与实现Collection相比,它在序列类上所施加的约束也少的多

package object;
//: holding/NonCollectionSequence.java
import typeinfo.pets.*;
import java.util.*;

class PetSequence {
  protected Pet[] pets = Pets.createArray(8);
}

public class NonCollectionSequence extends PetSequence {
     public Iterator<Pet> iterator() {
            return new Iterator<Pet>() {
              private int index = 0;
              public boolean hasNext() {
                return index < pets.length;
              }
              public Pet next() { return pets[index++]; }
              public void remove() { // Not implemented
                throw new UnsupportedOperationException();
              }
            };
  }
  public static void main(String[] args) {
    NonCollectionSequence nc = new NonCollectionSequence();
    InterfaceVsIterator.display(nc.iterator()); //NonCollectionSequence通过实现Iterator匿名类实现了Iterator
  }
} /* Output:
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
*///:~

 

posted @ 2019-01-17 20:15  江期玉  阅读(531)  评论(0编辑  收藏  举报