Yesterday i started reading Java Collections by John Zukowski.
Nice book written by John Zukowski.
Few important quotations i wanted to share from the next 2 chapters (3-4).
1) You can think of Java vectors as dynamically sized arrays with synchronized access. They prove to be very useful if you don't know the size of the array in advance, or you just need one that can change sizes over the lifetime of a program. Any object can be stored within a vector: these items are called elements. The one exception is that primitive data elements may not be stored in vectors, but since they aren't objects, this isn't really an exception.
Creating Vectors
You can use one of four constructors to create a Vector. For the first three constructors, an empty vector is created with an initial capacity of ten unless explicitly specified. When that space becomes too small, the vector will double in size unless a different capacity increment is specified.
public Vector()
public Vector(int initialCapacity)
public Vector(int initialCapacity, int capacityIncrement)
The reason for the different constructors is basically performance. If you know the approximate size beforehand, try to size the vector to that size to start. Otherwise, each time the vector size exceeds its capacity,a new internal array is created, which copies all the original elements to the larger new array. Creating a new array and copying the elements takes time, thus increasing the time it takes to add elements to the array.
2) Adding in the Middle
While the first two methods always add elements to the end of the vector, there are times when you wish to insert elements at arbitrary positions and move the remaining elements down. There are two methods for doing this, shown below, with arguments in the opposite order:
public void add(int index, Object element)
public void insertElementAt(Object element, int index)
3) An ArrayIndexOutOfBoundsException will be thrown if you try to add an element to a negative position or at some point beyond the last position of the vector. Adding an element at an arbitrary position beyond the end of the vector doesn't cause the vector to resize, as some people might think.
4) Removing Single Elements
Aside from clearing out an entire vector, you can also remove an element at a specific position with remove() or removeElementAt():
public Object remove(int index)
public void removeElementAt(int index)
As long as the index is valid (not less than zero or beyond the end, both of which trigger the throwing of an ArrayIndexOutOfBoundsException), the vector capacity stays the same. However, the internal contents shift to fill the vacated space, placing a null element at the end and decreasing the size by one. The difference between the two methods is that remove() returns the object removed, while removeElementAt() doesn't.If you don't know where an element is and you just want to remove it, you can pass the object to evict to either of the remove() or removeElement() methods:
public boolean remove(Object element)
public boolean removeElement(Object element)
5) Removing a Range of Elements
The last of the removal methods, removeRange(), is protected and only directly callable if you subclass vector:
protected void removeRange(int fromIndex, int toIndex)
It permits you to remove a whole set of items from the middle of a vector while performing only one shift of all the remaining elements.
6) Getting by Index
Like most functionality in the Vector class, there are two methods that do this: get() and elementAt(). Both of these methods allow you to fetch the element at a specific index, which is indexed like an array, starting from zero, as shown here:
public Object get(int index)
public Object elementAt(int index)
When getting an element from a vector, the element is always returned as an Object. You need to cast it to the appropriate type in order to work with it as the more specific type. Until Java supports parameterized types,vectors are not restricted to store only certain types. Instead, you always have to work with objects. The following example demonstrates this with a simple String object:
Vector v = new Vector();
v.add("Hello");
String s = (String)v.get(0);
7) Enumerating through the Elements
While the preceding example provides a relatively quick way to go through each element, it isn't particularly flexible if you later decide to change your data structure to something other than a Vector. A more flexible way is to use the Enumeration returned from the elements() method:
public Enumeration elements().
In short, it has two methods: hasMoreElements() and nextElement(). The first checks to see if there are any more elements in the vector, while the second returns the next element if it is there. You'll get a NoSuchElementException thrown if you call nextElement() after
hasMoreElements() returns false.
To perform the same operation to visit all elements of a vector, you can use the following construct:
Vector v = . . .
Enumeration e = v.elements();
while (e.hasMoreElements()) {
process(e.nextElement());
}
8) Checking for Position from End
The lastIndexOf() method allows you to search in reverse order from the end or some other position, rather than searching forward from the beginning:
public int lastIndexOf(Object element)
public int lastIndexOf(Object element, int index)
9) Removing Elements
To remove an element from the stack you call the pop() method:
public Object pop()
This takes the element at the top of the stack, removes it, and returns it. If the stack is empty when called, you
will get the runtime EmptyStackException thrown.
To avoid getting an EmptyStackException thrown, you should see if the stack is empty before calling pop().
This is done by calling the empty() method:
public boolean empty()
If the size of the stack is zero, true is returned; otherwise, false is returned.
About the Author
John Zukowski has been involved with the Java platform since it was just called Java, 11 years and running, since 1995. He is actively working with SavaJe Technologies to finish up the JavaOne 2006 device of show: the Jasper S20 mobile phone. He currently writes a monthly column for Sun’s Core Java Technologies Tech Tips and Technology Fundamentals Newsletter. He has contributed content to numerous other sites, including jGuru, DevX, Intel, and JavaWorld. He has written many other popular titles on Java, including Java AWT Reference (O’Reilly), Mastering Java 2 (Sybex), Borlands’ JBuilder: No Experience Required (Sybex), Learn Java with JBuilder 6 (Apress), Java Collections (Apress), and The Definitive Guide to Swing (Apress).
Tuesday, 9 December 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment