Почему метод не содержит информации о типе последовательности?
Читаю Брюса Эккеля "Философия Java", стр. 338
В качестве другого примера рассмотрим создание метода вывода содержимого, не зависящего от контейнера:
//: holding/CrossContainerIteration.java import typeinfo.pets.*j import java.util.*j public class CrossContainerIteration { 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 main(String[] args) { ArrayList<Pet> pets = Pets.arrayList(8); LinkedList<Pet> petsLL = new LinkedList<Pet>(pets); HashSet<Pet> petsHS = new HashSet<Pet>(pets); TreeSet<Pet> petsTS = new TreeSet<Pet>(pets); display(pets.iterator()); display(petsLL.iterator()); display(petsHS.iterator()); display(petsTS.iterator()); } } /* Output: 0:Rat l:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 0:Rat l:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 4:Pug 6:Pug 3:Mutt l:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat 5:Cymric 2:Cymric 7:Manx l:Manx 3:Mutt 6:Pug 4:Pug 0:Rat *///:~Обратите внимание: метод display() не содержит информации о типе последовательности.
Почему автор говорит что display не содержит информации о типе последователь
ности, ведь в самом входящем аргументе метода задан тип display(Iterator<Pet> it) ? Да и внутри метода указано Pet p
Ответы (1 шт):
У Эккеля эти понятия синонимичны: List называется и контейнером последовательности:
the library has different types of containers for different needs: several different kinds of
Listclasses (to hold sequences)
и последовательностью:
different containers have different efficiencies for certain operations. For example, there are two basic types of List:
ArrayListandLinkedList. Both are simple sequences that can have identical interfaces and external behaviors
источник: Bruce Eckel, Thinking in Java 4th Edition, Dec 2007
В данном примере типизированный итератор Iterator<Pet> позволяет абстрагироваться и от типа контейнера/коллекции (Set / List), и от конкретной реализации этих контейнеров / вида последовательности (HashSet / TreeSet или ArrayList / LinkedList).