java collection和Iterator

   Collection是描述全部 序列容器的共性的根接口,它能夠被認爲是一個"附屬接口",即由於要表示其餘若干個接口的共性而出現的接口,另外,java.uitl.AbstaractCollection類提供了Collection的默認實現,使得你能夠建立AbstractCollection的子類型,而其中沒有沒必要要的重複java

  使用接口描述的一個理由是它可使咱們可以建立更通用的代碼,經過針對接口而非具體實現來編寫代碼,咱們的代碼能夠應用於任何實現了Collection的類--這也就使得一個新類能夠選擇去實現Collection接口,以便咱們可使用它ui

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相比花費的代價略微減少spa

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相比,它在序列類上所施加的約束也少的多code

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
*///:~
相關文章
相關標籤/搜索