这一章主要要记住各个对象的方法,至少理解明白用途:
List:一些方法如下
List<Pet> pets = Pets.arrayList(7);
pets.add(h); // Automatically resizes
print("3: " + pets.contains(h));
pets.remove(h); // Remove by object
Pet p = pets.get(2);
print("5: " + pets.indexOf(cymric));
print("6: " + pets.remove(cymric));
print("8: " + pets);
pets.add(3, new Mouse()); // Insert at an index
List<Pet> sub = pets.subList(1, 4);
print("10: " + pets.containsAll(sub));
Collections.sort(sub); // In-place sort
print("11: " + pets.containsAll(sub));
Collections.shuffle(sub, rand); // Mix it up
print("12: " + pets.containsAll(sub));
List<Pet> copy = new ArrayList<Pet>(pets);
sub = Arrays.asList(pets.get(1), pets.get(4));
copy.retainAll(sub);
copy = new ArrayList<Pet>(pets); // Get a fresh copy
copy.remove(2); // Remove by index
copy.removeAll(sub); // Only removes exact objects
copy.set(1, new Mouse()); // Replace an element
copy.addAll(2, sub); // Insert a list in the middle
pets.clear(); // Remove all elements
print("20: " + pets.isEmpty());
pets.addAll(Pets.arrayList(4));
Object[] o = pets.toArray();
Pet[] pa = pets.toArray(new Pet[0]);
print("23: " + pa[3].id());
迭代器Iteraor:可以遍历并选择序列中的对象,客户端程序员不必知道或关心该序列底层的结构的一个对象。迭代器是一个对象!迭代器统一了对容器的访问方式。
1、使用方法Iterator要求容器返回一个Iterator
2、使用next()获得序列中的对象
3、使用hasNext()检查序列中是否还有元素
4、使用remove()将迭代器新近返回的元素删除
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());
}
LisrIterator:Iterator的子类型。ListIterator可以双向移动,可以产生前一个元素和后一个元素的索引。可以用set()方法替换它访问过的最后一个元素。可以调用ListIterator()产生一个指向List开始的一个ListIterator,ListIterator(n)开始指向第n个的元素的ListIterator。
public class ListIteration {
public static void main(String[] args) {
List<Pet> pets = Pets.arrayList(8);
ListIterator<Pet> it = pets.listIterator();
while(it.hasNext())
System.out.print(it.next() + ", " + it.nextIndex() +
", " + it.previousIndex() + "; ");
System.out.println();
// Backwards:
while(it.hasPrevious())
System.out.print(it.previous().id() + " ");
System.out.println();
System.out.println(pets);
it = pets.listIterator(3);
while(it.hasNext()) {
it.next();
it.set(Pets.randomPet());
}
System.out.println(pets);
}
} /* Output:
Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7;
7 6 5 4 3 2 1 0
[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx]
[Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, EgyptianMau]
*///:~
LinkedList:插入移除比ArrayList高效,随机访问慢。LinkedList有使用栈队列和双端队列的方法。
public class LinkedListFeatures {
public static void main(String[] args) {
LinkedList<Pet> pets =
new LinkedList<Pet>(Pets.arrayList(5));
print(pets);
// Identical:
print("pets.getFirst(): " + pets.getFirst());
print("pets.element(): " + pets.element());
// Only differs in empty-list behavior:
print("pets.peek(): " + pets.peek());
// Identical; remove and return the first element:
print("pets.remove(): " + pets.remove());
print("pets.removeFirst(): " + pets.removeFirst());
// Only differs in empty-list behavior:
print("pets.poll(): " + pets.poll());
print(pets);
pets.addFirst(new Rat());
print("After addFirst(): " + pets);
pets.offer(Pets.randomPet());
print("After offer(): " + pets);
pets.add(Pets.randomPet());
print("After add(): " + pets);
pets.addLast(new Hamster());
print("After addLast(): " + pets);
print("pets.removeLast(): " + pets.removeLast());
}
} /* Output:
[Rat, Manx, Cymric, Mutt, Pug]
pets.getFirst(): Rat
pets.element(): Rat
pets.peek(): Rat
pets.remove(): Rat
pets.removeFirst(): Manx
pets.poll(): Cymric
[Mutt, Pug]
After addFirst(): [Rat, Mutt, Pug]
After offer(): [Rat, Mutt, Pug, Cymric]
After add(): [Rat, Mutt, Pug, Cymric, Pug]
After addLast(): [Rat, Mutt, Pug, Cymric, Pug, Hamster]
pets.removeLast(): Hamster
*///:~
Stack:栈方法
class Stack<T> {
private LinkedList<T> storage = new LinkedList<T>();
public void push(T v) { storage.addFirst(v); }
public T peek() { return storage.getFirst(); }
public T pop() { return storage.removeFirst(); }
public boolean empty() { return storage.isEmpty(); }
public String toString() { return storage.toString(); }
}
public class StackTest {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
for(String s : "My dog has fleas".split(" "))
stack.push(s);
while(!stack.empty())
System.out.print(stack.pop() + " ");
}
} /* Output:
fleas has dog My
*/
Set:不保存重复元素。Set与Colllection具有完全一样的接口,只是行为不同。
public class SetOperations {
public static void main(String[] args) {
Set<String> set1 = new HashSet<String>();
Collections.addAll(set1, "A B C D E F G H I J K L".split(" "));
set1.add("M");
System.out.println("H: " + set1.contains("H"));
System.out.println("N: " + set1.contains("N"));
Set<String> set2 = new HashSet<String>();
Collections.addAll(set2, "H I J K L".split(" "));
System.out.println("set2 in set1: " + set1.containsAll(set2));
set1.remove("H");
System.out.println("set1: " + set1);
System.out.println("set2 in set1: " + set1.containsAll(set2));
set1.removeAll(set2);
System.out.println("set2 removed from set1: " + set1);
Collections.addAll(set1, "X Y Z".split(" "));
System.out.println("'X Y Z' added to set1: " + set1);
}
} /*
* Output: H: true N: false set2 in set1: true set1: [D, K, C, B, L, G, I, M, A,
* F, J, E] set2 in set1: false set2 removed from set1: [D, C, B, G, M, A, F, E]
* 'X Y Z' added to set1: [Z, D, C, B, G, M, A, F, Y, X, E]
*/// :~
Map:对象对象映射起来。
public class MapOfList {
public static Map<Person, List<? extends Pet>> petPeople = new HashMap<Person, List<? extends Pet>>();
static {
petPeople.put(new Person("Dawn"),
Arrays.asList(new Cymric("Molly"), new Mutt("Spot")));
petPeople.put(new Person("Kate"), Arrays.asList(new Cat("Shackleton"),
new Cat("Elsie May"), new Dog("Margrett")));
petPeople.put(new Person("Marilyn"), Arrays.asList(new Pug(
"Louie aka Louis Snorkelstein Dupree"), new Cat(
"Stanford aka Stinky el Negro"), new Cat("Pinkola")));
petPeople.put(new Person("Luke"),
Arrays.asList(new Rat("Fuzzy"), new Rat("Fizzy")));
petPeople.put(new Person("Isaac"), Arrays.asList(new Rat("Freckly")));
}
public static void main(String[] args) {
print("People: " + petPeople.keySet());
print("Pets: " + petPeople.values());
for (Person person : petPeople.keySet()) {
print(person + " has:");
for (Pet pet : petPeople.get(person))
print(" " + pet);
}
}
} /*
* Output: People: [Person Luke, Person Marilyn, Person Isaac, Person Dawn,
* Person Kate] Pets: [[Rat Fuzzy, Rat Fizzy], [Pug Louie aka Louis Snorkelstein
* Dupree, Cat Stanford aka Stinky el Negro, Cat Pinkola], [Rat Freckly],
* [Cymric Molly, Mutt Spot], [Cat Shackleton, Cat Elsie May, Dog Margrett]]
* Person Luke has: Rat Fuzzy Rat Fizzy Person Marilyn has: Pug Louie aka Louis
* Snorkelstein Dupree Cat Stanford aka Stinky el Negro Cat Pinkola Person Isaac
* has: Rat Freckly Person Dawn has: Cymric Molly Mutt Spot Person Kate has: Cat
* Shackleton Cat Elsie May Dog Margrett
*/// :~