您的位置:首页 > 移动开发 > Objective-C

第十一章: Collections of Objects (2.1容器类)

2005-12-15 21:05 561 查看
3[/b])[/b]Introduction to containers
The Java 2 container library takes the issue of “holding your objects” and divides it into two distinct concepts:
a、 Collection: a group of individual elements, often with some rule applied to them. A List must hold the elements in a particular sequence, and a Set cannot have any duplicate elements.
b、 Map: a group of key-value object pairs. it’s convenient to look at portions of a Map by creating a Collection to represent that portion. Thus, a Map can return a Set of its keys, a Collection of its values, or a Set of its pairs.
3.1)[/b] Printing containers
// Containers print themselves automatically.
import com.bruceeckel.simpletest.*;
import java.util.*;
public class PrintingContainers {
private static Test monitor = new Test();
static Collection fill(Collection c) {
c.add("dog");
c.add("dog");
c.add("cat");
return c;
}
static Map fill(Map m) {
m.put("dog", "Bosco");
m.put("dog", "Spot");
m.put("cat", "Rags");
return m;
}
public static void main(String[] args) {
System.out.println(fill(new ArrayList()));
System.out.println(fill(new HashSet()));
System.out.println(fill(new HashMap()));
monitor.expect(new String[] {
"[dog, dog, cat]",
"[dog, cat]",
"{dog=Spot, cat=Rags}"
});
}
} ///:~
The List holds the objects exactly as they are entered, without any reordering or editing. The Set, however, only accepts one of each object, and it uses its own internal ordering method ,And the Map also only accepts one of each type of item, based on the key, and it also has its own internal ordering and does not care about the order in which you enter the items. If maintaining the insertion sequence is important, you can use a LinkedHashSet or LinkedHashMap
4)[/b] Iterators(迭代器)
An iterator is an object whose job is to move through a sequence of objects and select each object in that sequence without the client programmer knowing or caring about the underlying structure of that sequence.
Iterator -- can move in only one direction
a、 Ask a container to hand you an Iterator using a method called iterator( ).This Iterator will be ready to return the first element in the sequence on your first call to its next( ) method.
b、 Get the next object in the sequence with next( ).
c、 See if there are any more objects in the sequence with hasNext( ).
d、 Remove the last element returned by the iterator with remove( ).
5)[/b] Container taxonomy(容器分类学)


6)[/b] Collection functionality
The following table shows everything you can do with a Collection, and thus, everything you can do with a Set or a List. Notice that there’s no get( ) method for random-access element selection. That’s because Collection also includes Set, Thus, if you want to examine the elements of a Collection, you must use an iterator.
[align=center]
boolean add(Object)
Ensures that the container holds the argument. Returns false if it doesn’t add the argument.
boolean
addAll(Collection)
Adds all the elements in the argument. Returns true if any elements were added. (“Optional.”)
void clear( )
Removes all the elements in the container. (“Optional.”)
boolean
contains(Object)
true if the container holds the argument.
boolean containsAll(Collection)
true if the container holds all the elements in the argument.
boolean isEmpty( )
true if the container has no elements.
Iterator iterator( )
Returns an Iterator that you can use to move through the elements in the container.
boolean
remove(Object)
If the argument is in the container, one instance of that element is removed. Returns true if a removal occurred. (“Optional.”)
boolean removeAll(Collection)
Removes all the elements that are contained in the argument. Returns true if any removals occurred. (“Optional.”)
boolean retainAll(Collection)
Retains only elements that are contained in the argument (an “intersection” from set theory). Returns true if any changes occurred. (“Optional.”)
int size( )
Returns the number of elements in the container.
Object[] toArray( )
Returns an array containing all the elements in the container.
Object[]
toArray(Object[] a)
Returns an array containing all the elements in the container, whose type is that of the array a rather than plain Object (you must cast the array to the right type).
[/align]7)[/b] List functionality
[align=center]
List (interface)
Order is the most important feature of a List; it promises to maintain elements in a particular sequence. List adds a number of methods to Collection that allow insertion and removal of elements in the middle of a List. (This is recommended only for a LinkedList.) A List will produce a ListIterator, and by using this you can traverse the List in both directions, as well as insert and remove elements in the middle of the List.
ArrayList*
A List implemented with an array. Allows rapid random access to elements, but is slow when inserting and removing elements from the middle of a list. ListIterator should be used only for back-and-forth traversal of an ArrayList, but not for inserting and removing elements, which is expensive compared to LinkedList.
LinkedList
Provides optimal sequential access, with inexpensive insertions and deletions from the middle of the List. Relatively slow for random access. (Use ArrayList instead.) Also has addFirst( ), addLast( ), getFirst( ), getLast( ), removeFirst( ), and removeLast( ) (which are not defined in any interfaces or base classes) to allow it to be used as a stack, a queue, and a deque.
[/align]8)
[/b]The Set is exactly a Collection—it just has different behavior.
[/b][align=center]
Set (interface)
Each element that you add to the Set must be unique; otherwise, the Set doesn’t add the duplicate element. Objects added to a Set must define equals( ) to establish object uniqueness. Set has exactly the same interface as Collection. The Set interface does not guarantee that it will maintain its elements in any particular order.
HashSet*
For Sets where fast lookup time is important. Objects must also define hashCode( ).
TreeSet
An ordered Set backed by a tree. This way, you can extract an ordered sequence from a Set.
LinkedHashSet
(JDK 1.4)
Has the lookup speed of a HashSet, but maintains the order in which you add the elements (the insertion order), internally using a linked list. Thus, when you iterate through the Set, the results appear in insertion order.
[/align]无论用哪种set都应该定义equals(),但只有在把对象放进HashSet的时侯,你才需要定义hashCode()
SortedSet--[/b] the elements are guaranteed to be in sorted order, additional functionality to be provided with these methods in the SortedSet interface:
Comparator comparator( ): Produces the Comparator used for this Set, or null for natural ordering.
Object first( ): Produces the lowest element.
Object last( ): Produces the highest element.
SortedSet subSet(fromElement, toElement): Produces a view of this Set with elements from fromElement, inclusive, to toElement, exclusive.
SortedSet headSet(toElement): Produces a view of this Set with elements less than toElement.
SortedSet tailSet(fromElement): Produces a view of this Set with elements greater than or equal to fromElement.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: