`
leonzhx
  • 浏览: 796708 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Chapter 11. Holding Your Objects -- Thinking in Java

阅读更多

1) An array has a fixed size, and in the more general case, you won’t know at the time you’re writing the program how many objects you’re going to need.

 

2) The java.util library has a reasonably complete set of container classes to solve this problem, the basic types of which are List, Set, Queue, and Map. These types of objects are also known as collection classes, but the Java library uses the name Collection to refer to a particular subset of the library.

 

3) Unlike with arrays, you can put in any number of objects and you don’t need to worry about how big to make the container while you’re writing the program.

 

4) Special Java SE5 annotation is used to suppress the warning. Annotations start with an '@' sign, and can take an argument; @SuppressWarnings("unchecked") indicates that "unchecked" warnings only should be suppressed.

 

5) To define an ArrayList intended to hold Apple objects, you say ArrayList<Apple> instead of just ArrayList. The angle brackets surround the type parameters (there may be more than one), which specify the type(s) that can be held by that instance of the container. With generics, you’re prevented, at compile time, from putting the wrong type of object into a container. With generics you not only know that the compiler will check the type of object that you put into a container, but you also get cleaner syntax when using the objects in the container( no need of type cast when retrieving objects from the container).

 

6) The default toString( ) method of Object prints the class name followed by the unsigned hexadecimal representation of the hash code of the object (generated by the hashCode( ) method).

 

7) The Java container library divides it into two distinct concepts, expressed as the basic interfaces of the library:
    a. Collection: a sequence of individual elements with one or more rules applied to them. A List must hold the elements in the way that they were inserted, a Set cannot have duplicate elements, and a Queue produces the elements in the order determined by a queuing discipline (usually the same order in which they are inserted).
    b. Map: a group of key-value object pairs, allowing you to look up a value using a key. An ArrayList allows you to look up an object using a number, so in a sense it associates numbers to objects. A map allows you to look up an object using another object. It’s also called an associative array, because it associates objects with other objects, or a dictionary, because you look up a value object using a key object just like you look up a definition using a word.

 

8) The Collection interface generalizes the idea of a sequence—a way of holding a group of objects.

 

9) The name of the add( ) method suggests that it puts a new element in the Collection. However, the documentation carefully states that add( ) "ensures that this Collection contains the specified element." This is to allow for the meaning of Set, which adds the element only if it isn’t already there. With an ArrayList, or any sort of List, add( ) always means "put it in," because Lists don’t care if there are duplicates.

 

10) All Collections can be traversed using the foreach syntax.

 

11) Arrays.asList( ) takes either an array or a comma-separated list of elements (using varargs) and turns it into a List object. Collections.addAll( ) takes a Collection object and either an array or a comma-separated list and adds the elements to the Collection.

 

12) The constructor for a Collection can accept another Collection which it uses for initializing itself, so you can use Arrays.asList( ) to produce input for the constructor. However, Collections.addAll( ) runs much faster, and it’s just as easy to construct the Collection with no elements and then call Collections.addAll( ), so this is the preferred approach. The Collection.addAll( ) member method can only take an argument of another Collection object, so it is not as flexible as Arrays.asList( ) or Collections.addAll( ), which use variable argument lists.

 

13) It’s also possible to use the output of Arrays.asList( ) directly, as a List, but the underlying representation in this case is the array, which cannot be resized. If you try to add( ) or delete( ) elements in such a list, that would attempt to change the size of an array, so you’ll get an "Unsupported Operation" error at runtime.

 

14) A limitation of Arrays.asList( ) is that it takes a best guess about the resulting type of the List, and doesn’t pay attention to what you’re assigning it to. ( the lowest common ancestor) But it’s possible to insert a "hint" in the middle of Arrays.asList( ), to tell the compiler what the actual target type should be for the resulting List type produced by Arrays.asList( ):  Arrays.<Type>asList( ) This is called an explicit type argument specification.

 

15) You must use Arrays.toString( ) to produce a printable representation of an array, but the containers print nicely without any help. A Collection is printed surrounded by square brackets, with each element separated by a comma. A Map is surrounded by curly braces, with each key and value associated with an equal sign (keys on the left, values on the right).

 

16) Map.put(key, value) adds a value (the thing you want) and associates it with a key (the thing you look it up with). Map.get(key) produces the value associated with that key.

 

17) The List interface adds a number of methods to Collection that allow insertion and removal of elements in the middle of a List.

 

18) There are two types of List:
    a. The basic ArrayList, which excels at randomly accessing elements, but is slower when inserting and removing elements in the middle of a List.
    b. The LinkedList, which provides optimal sequential access, with inexpensive insertions and deletions from the middle of the List. A LinkedList is relatively slow for random access, but it has a larger feature set than the ArrayList.

 

19) You can find out whether an object is in the list using the contains( ) method. If you want to remove an object, you can pass that object’s reference to the remove( ) method. Also, if you have a reference to an object, you can discover the index number where that object is located in the List using indexOf( ).

 

20) When deciding whether an element is part of a List, discovering the index of an element, and removing an element from a List by reference, the equals( ) method (part of the root class Object) is used.

 

21) subList( ) produces a list backed by the original list. Therefore, changes in the returned list are reflected in the original list, and vice versa. Order is not important for containsAll() , Collections.sort( ) and Collections.shuffle( ) on List doesn’t affect the outcome of containsAll( ). The retainAll( ) method is effectively a "set intersection" operation and the resulting behavior depends on the equals( ) method.

 

22) You can convert any Collection to an array using toArray( ). This is an overloaded method; the no-argument version returns an array of Object, but if you pass an array of the target type to the overloaded version, it will produce an array of the type specified (assuming it passes type checking and this doesn't apply to the raw type of Collection, raw type of Collection will always return Object[]). If the argument array is too small to hold all the objects in the List , toArray( ) will create a new array of the appropriate size.

 

23) An iterator is an object whose job is to move through a sequence and select each object in that sequence without the client programmer knowing or caring about the underlying structure of that sequence. In addition, an iterator is usually what’s called a lightweight object: one that’s cheap to create.

 

24) There’s not much you can do with an Iterator except:
    a. Ask a Collection to hand you an Iterator using a method called iterator( ). That Iterator will be ready to return the first element in the sequence.
    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( ).

 

25) The true power of the Iterator: the ability to separate the operation of traversing a sequence from the underlying structure of that sequence. For this reason, we sometimes say that iterators unify access to containers.

 

26) The ListIterator is a more powerful subtype of Iterator that is produced only by List classes. While Iterator can only move forward, ListIterator is bidirectional. It can also produce the indexes of the next and previous elements relative to where the iterator is pointing in the list, and it can replace the last element that it visited using the set( ) method. You can produce a ListIterator that points to the beginning of the List by calling listIterator( ), and you can also create a ListIterator that starts out pointing to an index n in the list by calling listIterator(n).

 

27) LinkedList also adds methods that allow it to be used as a stack, a Queue or a double-ended queue (deque). Some of these methods are aliases or slight variations of each other, to produce names that are more familiar within the context of a particular usage.

 

28) getFirst( ) and element( ) are identical—they return the head (first element) of the list without removing it, and throw NoSuchElementException if the List is empty. peek( ) is a slight variation of those two that returns null if the list is empty.

 

29) removeFirst( ) and remove( ) are also identical—they remove and return the head of the list, and throw NoSuchElementException for an empty list, and poll( ) is a slight variation that returns null if this list is empty.

 

30) addFirst( ) inserts an element at the beginning of the list. offer( ) is the same as add( ) and addLast( ). They all add an element to the tail (end) of a list. removeLast( ) removes and returns the last element of the list.

 

31) If you look at the Queue interface, you’ll see the offer( )element( ), peek( ), remove( ) and poll( ) methods that were added to LinkedList in order that it could be a Queue implementation.

 

32) A stack is sometimes referred to as a "last-in, first-out" (LIFO) container. It’s sometimes called a pushdown stack, because whatever you "push" on the stack last is the first item you can "pop" off of the stack.

 

33) The <T> after the class name tells the compiler that this will be a parameterized type, and that the type parameter—the one that will be substituted with a real type when the class is used—is T.

 

34) HashSet implementation is optimized for rapid lookup.TreeSet keeps the objects in ascending comparison order, or a LinkedHashSet keeps the objects in the order in which they were added.

 

35) Set has the same interface as Collection,

 

36) TreeSet keeps elements sorted into a red-black tree data structure, whereas HashSet uses the hashing function. LinkedHashSet also uses hashing for lookup speed, but appears to maintain elements in insertion order using a linked list.

 

37) For Map, the get( ) method returns null if the key is not already in the container. The keySet( ) method produces a Set of all the keys, which is usually used in the foreach statement to iterate through the Map.

 

38) A queue is typically a “first-in, first-out" (FIFO) container. That is, you put things in at one end and pull them out at the other, and the order in which you put them in will be the same order in which they come out.

 

39) offer( ) is one of the Queue-specific methods; it inserts an element at the tail of the queue if it can, otherwise returns false. Both peek( ) and element( ) return the head of the queue without removing it, but peek( ) returns null if the queue is empty and element( ) throws NoSuchElementException. Both poll( ) and remove( ) remove and return the head of the queue, but poll( ) returns null if the queue is empty, while remove( ) throws NoSuchElementException.

 

40) A priority queue says that the element that goes next is the one with the greatest need (the highest priority). PriorityQueue was added in Java SE5 to provide an automatic implementation for this behavior.

 

41) When you offer( ) an object onto a PriorityQueue, that object is sorted into the queue. The default sorting uses the natural order of the objects in the queue, but you can modify the order by providing your own Comparator. The PriorityQueue ensures that when you call peek( ), poll( ) or remove( ), the element you get will be the one with the highest priority (least one with respect to the specified ordering).

 

42) For PriorityQueue, the lowest values have the highest priority (in the case of String, spaces also count as values and are higher in priority than letters). Integer, String and Character work with PriorityQueue because these classes already have natural ordering built in. If you want to use your own class in a PriorityQueue, you must include additional functionality to produce natural ordering, or provide your own Comparator. Collections.reverseOrder( ) (added in Java SE5) produced reverse-order Comparator.

 

43) Iterator and Collection are two ways to express commonality between containers. The use of Iterator becomes compelling when you implement a foreign class, one that is not a Collection. (to avoid implementing unnecessary methods event inheriting from AbstractCollection)

 

44) Working with foreach is a characteristic of all Collection objects. The reason that this works is that Java SE5 introduced a new interface called Iterable which contains an iterator( ) method to produce an Iterator, and the Iterable interface is what foreach uses to move through a sequence. So if you create any class that implements Iterable, you can use it in a foreach statement.

 

45) System.getenv( )(added in Java SE5) returns a Map, entrySet( ) produces a Set of Map.Entry elements.

 

46) A foreach statement works with an array or anything Iterable, but that doesn’t mean that an array is automatically an Iterable.

 

47) Arrays.asList( ) produces a List object that uses the underlying array as its physical implementation. If you do anything to that List that modifies it, and you don’t want the original array modified, you should make a copy into another container.

 

48) HashMap is designed for rapid access, whereas a TreeMap keeps its keys in sorted order, and thus is not as fast as a HashMap. A LinkedHashMap keeps its elements in insertion order, but provides rapid access with hashing.

 

49) There’s no need to use the legacy classes Vector, Hashtable, and Stack in new code.

 



 

  • 大小: 35.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics