Download The Vector

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Data Structures (2nd edition) - End of the World Production, LLC.
1 av 2
http://www.theparticle.com/javadata2.html
The Vector...
The java.util.Vector class is provided by the Java API, and is one of the most useful array
based data storage classes I've ever seen. The information provided here is as far as JDK 1.2
goes, future versions may have other implementations; still, the functionality should remain the
same. A vector, is a growing array; as more and more elements are added onto it, the array
grows. There is also a possibility of making the array smaller.
But wait a minute, all this time I've been saying that arrays can't grow or shrink, and it seems
Java API has done it. Not quite. The java.util.Vector class doesn't exactly grow, or shrink.
When it needs to do these operations, it simply allocates a new array (of appropriate size), and
copies the contents of the old array into the new array. Thus, giving the impression that the array
has changed size.
All these memory operations can get quite expensive if a Vector is used in a wrong way. Since
a Vector has a similar architecture to the array stack we've designed earlier, the best and fastest
way to implement a Vector is to do stack operations. Usually, in programs, we need a general
data storage class, and don't really care about the order in which things are stored or retrieved;
that's where java.util.Vector comes in very useful.
Using a Vector to simulate a queue is very expensive, since every time you insert or remove,
the entire array has to be copied (not necessarily reallocated but still involves lots of useless
work).
Vector allows us to view it's insides using an Enumerator; a class to go through objects. It is
very useful to first be able to look what you're looking for, and only later decide whether you'd
like to remove it or not. A sample program that uses java.util.Vector for it's storage follows.
import java.io.*;
import java.util.*;
class pVectorTest{
public static void main(String[] args){
Vector v = new Vector(15);
Integer j = null;
int i;
System.out.println("starting...");
for(i=0;i<10;i++){
j = new Integer((int)(Math.random() * 100));
v.addElement(j);
System.out.println("addElement: " + j);
}
System.out.println("size: "+v.size());
System.out.println("capacity: "+v.capacity());
Enumeration enum = v.elements();
while(enum.hasMoreElements())
System.out.println("enum: "+(Integer)enum.nextElement());
}
}
System.out.println("Done ;-)");
The example above should be self evident (if you paid attention when I showed test programs
for the previous data structures). The main key difference is that this one doesn't actually remove
objects at the end; we just leave them inside. Removal can be accomplished very easily, and if
you'll be doing anything cool with the class, you'll sure to look up the API specs.
Printing is accomplished using an Enumerator; which we use to march through every element
printing as we move along. We could also have done the same by doing a for loop, going from 0
to v.size(), doing a v.elementAt(int) every time through the loop. The output from the above
program follows:
2007-09-19 02:41
Java Data Structures (2nd edition) - End of the World Production, LLC.
2 av 2
http://www.theparticle.com/javadata2.html
program follows:
starting...
addElement:
addElement:
addElement:
addElement:
addElement:
addElement:
addElement:
addElement:
addElement:
addElement:
size: 10
capacity: 15
enum: 9
enum: 5
enum: 54
enum: 49
enum: 60
enum: 81
enum: 8
enum: 91
enum: 76
enum: 81
Done ;-)
9
5
54
49
60
81
8
91
76
81
You should notice that when we print the size and capacity, they're different. The size is the
current number of elements inside the Vector, and the capacity, is the maximum possible
without reallocation.
A trick you can try yourself when playing with the Vector is to have Vectors of Vectors (since
Vector is also an Object, there shouldn't be any problems of doing it). Constructs like that can
lead to some interesting data structures, and even more confusion. Just try inserting a Vector
into a Vector ;-)
I guess that covers the Vector class. If you need to know more about it, you're welcome to
read the API specs for it. I also greatly encourage you to look at java.util.Vector source, and
see for yourself what's going on inside that incredibly simple structure.
2007-09-19 02:41
Java Generic Collections Tutorial: Vector
1 av 1
http://www.deitel.com/articles/java_tutorials/20051209/Vector.html
of Chapter 19,
Collections, from our textbook Java How to Program, 6/e. These tutorials may refer to other chapters or
sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J.,
JAVA HOW TO PROGRAM, ©2005, pp.911-922. Electronically reproduced by permission of Pearson
Education, Inc., Upper Saddle River, New Jersey.]
19.5.3 Vector
Like
ArrayList,
class
Vector
provides the capabilities of array-like data structures that can resize themselves dynamically. Recall that
class ArrayList’s behavior and capabilities are similar to those of class Vector, except that
ArrayLists do not provide synchronization by default. We cover class Vector here primarily because it is
the superclass of class Stack, which is presented in Section 19.7. At any time, a Vector contains a
number of elements that is less than or equal to its capacity. The capacity is the space that has been
reserved for the Vector’s elements. If a Vector requires additional capacity, it grows by a capacity
increment
that you specify or by a default capacity increment. If you do not specify a capacity increment or specify one
that is less than or equal to zero, the system will double the size of a Vector each time additional capacity
is needed.
Performance Tip 19.2
Inserting an element into a Vector whose current size is less than its capacity is a relatively fast
operation.
Performance Tip 19.3
Inserting an element into a Vector that needs to grow larger to accommodate the new element is a
relatively slow operation.
Performance Tip 19.4
The default capacity increment doubles the size of the Vector. This may seem a waste of storage, but it is
actually an efficient way for many Vectors to grow quickly to be “about the right size.” This operation is
much more efficient than growing the Vector each time by only as much space as it takes to hold a single
element. The disadvantage is that the Vector might occupy more space than it requires. This is a classic
example of the space–time trade-off.
Performance Tip 19.5
If storage is at a premium, use Vector method trimToSize to trim a Vector’s capacity to the
Vector’s exact size. This operation optimizes a Vector’s use of storage. However, adding another
element to the Vector will force the Vector to grow dynamically (again, a relatively slow
operation)—trimming leaves no room for growth.
Page 1 | 2 | 3
Other Tutorials in this series:
Part 1: Introduction to Lists
Part 2: ArrayList and Iterator
Part 3: LinkedList
Part 4: Vector (Your are here)
2007-09-19 02:34
Java Generic Collections Tutorial: Vector (Page 2)
1 av 2
http://www.deitel.com/articles/java_tutorials/20051209/Vector_Page2...
Vector (Continued)
Figure 19.6 demonstrates class Vector and several of its methods. For complete information on class
Vector, please visit java.sun.com/j2se/5.0/docs/api/java/util/Vector.html.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Fig. 19.6: VectorTest.java
// Using the Vector class.
import java.util.Vector;
import java.util.NoSuchElementException;
public class VectorTest
{
private static final String colors[] = { "red", "white", "blue" };
public VectorTest()
{
Vector< String > vector = new Vector< String >();
printVector( vector ); // print vector
// add elements to the vector
for ( String color : colors )
vector.add( color );
printVector( vector ); // print vector
// output the first and last elements
try
{
System.out.printf( "First element: %s\n", vector.firstElement());
System.out.printf( "Last element: %s\n", vector.lastElement() );
} // end try
// catch exception if vector is empty
catch ( NoSuchElementException exception )
{
exception.printStackTrace();
} // end catch
// does vector contain "red"?
if ( vector.contains( "red" ) )
System.out.printf( "\n\"red\" found at index %d\n\n",
vector.indexOf( "red" ) );
else
System.out.println( "\n\"red\" not found\n" );
vector.remove( "red" ); // remove the string "red"
System.out.println( "\"red\" has been removed" );
printVector( vector ); // print vector
// does vector contain "red" after remove operation?
if ( vector.contains( "red" ) )
System.out.printf(
"\"red\" found at index %d\n", vector.indexOf( "red" ) );
else
System.out.println( "\"red\" not found" );
// print the size and capacity of vector
System.out.printf( "\nSize: %d\nCapacity: %d\n", vector.size(),
vector.capacity() );
} // end Vector constructor
private void printVector( Vector< String > vectorToOutput )
{
if ( vectorToOutput.isEmpty() )
System out print( "vector is empty" ); // vectorToOutput is empty
2007-09-19 02:33
Java Generic Collections Tutorial: Vector (Page 2)
2 av 2
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
http://www.deitel.com/articles/java_tutorials/20051209/Vector_Page2...
System.out.print( vector is empty ); // vectorToOutput is empty
else // iterate through the elements
{
System.out.print( "vector contains: " );
// output elements
for ( String element : vectorToOutput )
System.out.printf( "%s ", element );
} // end else
System.out.println( "\n" );
} // end method printVector
public static void main( String args[] )
{
new VectorTest(); // create object and call its constructor
} // end main
} // end class VectorTest
vector is empty
vector contains: red white blue
First element: red
Last element: blue
"red" found at index 0
"red" has been removed
vector contains: white blue
"red" not found
Size: 2
Capacity: 10
Fig. 19.6
Vector class of package java.util.
Page 1 | 2 | 3
Other Tutorials in this series:
Part 1: Introduction to Lists
Part 2: ArrayList and Iterator
Part 3: LinkedList
Part 4: Vector (Your are here)
2007-09-19 02:33
Java Collections: Vector (Page 3)
1 av 2
http://www.deitel.com/articles/java_tutorials/20051209/Vector_Page3...
19.5.3 Vector (Continued)
The application’s constructor creates a Vector (line 13) of type String with an initial capacity of 10
elements and capacity increment of zero (the defaults for a Vector). Note that Vector is a generic class,
which takes one argument that specifies the type of the elements stored in the Vector. A capacity
increment of zero indicates that this Vector will double in size each time it needs to grow to accommodate
more
elements.
Class
Vector
provides three other constructors. The constructor that takes one integer argument creates an empty
Vector
with
the
initial
capacity
specified by that argument. The constructor that takes two arguments creates a Vector with the initial
capacity specified by the first argument and the capacity increment specified by the second argument.
Each
time
the
Vector
needs to grow, it will add space for the specified number of elements in the capacity increment. The
constructor that takes a Collection creates a copy of a collection’s elements and stores them in the
Vector. Line 18 calls Vector method add to add objects (Strings in this program) to the end of the
Vector. If necessary, the Vector increases its capacity to accommodate the new element. Class Vector
also
provides
a
method
add
that takes two arguments. This method takes an object and an integer and inserts the object at the
specified index in the Vector. Method set will replace the element at a specified position in the Vector
with a specified element. Method insertElementAt provides the same functionality as the method add that
takes two arguments, except that the order of the parameters is reversed. Line 25 calls Vector method
firstElement to return a reference to the first element in the Vector. Line 26 calls Vector method
lastElement to return a reference to the last element in the Vector. Each of these methods throws a
NoSuchElementException if there are no elements in the Vector when the method is called. Line 35
calls Vector method contains to determine whether the Vector contains "red". The method returns
true if its argument is in the Vector—otherwise, the method returns false. Method contains uses
Object method equals to determine whether the search key is equal to one of the Vector’s elements.
Many
classes
override
method
equals
to perform the comparisons in a manner specific to those classes. For example, class String declares
equals to compare the individual characters in the two Strings being compared. If method equals is
not overridden, the original version of method equals inherited from class Object is used.
Common Programming Error 19.4
Without overriding method equals, the program performs comparisons using operator == to determine
whether two references refer to the same object in memory.
Line 37 calls Vector method indexOf to determine the index of the first location in the Vector that
contains the argument. The method returns −1 if the argument is not found in the Vector. An overloaded
version of this method takes a second argument specifying the index in the Vector at which the search
should begin.
Performance Tip 19.6
Vector methods contains and indexOf perform linear searches of a Vector’s contents. These
searches are inefficient for large Vectors. If a program frequently searches for elements in a collection,
consider using one of the Java Collection API’s Map implementations (Section 19.10), which provide
high-speed searching capabilities.
Line 41 calls Vector method remove to remove the first occurrence of its argument from the Vector. The
method returns true if it finds the element in the Vector; otherwise, the method returns false. If the
element is removed, all elements after that element in the Vector shift one position toward the beginning
of the Vector to fill in the position of the removed element. Class Vector also provides method
removeAllElements to remove every element from a Vector and method removeElementAt to remove the
element at a specified index. Lines 53–54 use Vector methods size and capacity to determine the number
of elements currently in the Vector and the number of elements that can be stored in the Vector without
allocating more memory, respectively. Line 59 calls Vector method isEmpty to determine whether the
Vector is empty. The method returns true if there are no elements in the Vector; otherwise, the method
returns false. Lines 66–67 use the enhanced for statement to print out all elements in the vector. Among
the methods introduced in Fig. 19.6, firstElement, lastElement and capacity can be used only with
Vector. Other methods (e.g., add, contains, indexOf, remove, size and isEmpty) are declared by
List, which means that they can be used by any class that implements List, such as Vector.
Page 1 | 2 | 3
Other Tutorials in this series:
Part 1: Introduction to Lists
Part 2: ArrayList and Iterator
2007-09-19 02:32
Java Collections: Vector (Page 3)
2 av 2
http://www.deitel.com/articles/java_tutorials/20051209/Vector_Page3...
y st
te to
Part 3: LinkedList
Part 4: Vector (Your are here)
2007-09-19 02:32
Print this article
1 av 2
http://www.java-samples.com/forprinting.php?tutorialid=373
Vector example in Java
Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it
contains many legacy methods that are not part of the collections framework. With the release of Java 2, Vector was
reengineered to extend AbstractList and implement the List interface, so it now is fully compatible with collections.
Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)
The first form creates a default vector, which has an initial size of 10. The second form creates a vector whose initial
capacity is specified by size. The third form creates a vector whose initial capacity is specified by size and whose increment
is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward.
The fourth form creates a vector that contains the elements of collection c. This constructor was added by Java 2.
All vectors start with an initial capacity. After this initial capacity is reached, the next time that you attempt to store an
object in the vector, the vector automatically allocates space for that object plus extra room for additional objects. By
allocating more than just the required memory, the vector reduces the number of allocations that must take place. This
reduction is important, because allocations are costly in terms of time. The amount of extra space allocated during each
reallocation is determined by the increment that you specify when you create the vector. If you don't specify an increment,
the vector's size is doubled by each allocation cycle.
Vector defines these protected data members:
int capacityIncrement;
int elementCount;
Object elementData[ ];
The increment value is stored in capacityIncrement. The number of elements currently in the vector is stored in
elementCount. The array that holds the vector is stored in elementData.
Because Vector implements List, you can use a vector just like you use an ArrayList instance. You can also manipulate
one using its legacy methods. For example, after you instantiate a Vector, you can add an element to it by calling
addElement( ). To obtain the element at a specific location, call elementAt( ). To obtain the first element in the vector,
call firstElement( ). To retrieve the last element, call lastElement( ). You can obtain the index of an element by using
indexOf( ) and lastIndexOf( ). To remove an element, call removeElement( ) or removeElementAt( ).
The following program uses a vector to store various types of numeric objects. It demonstrates several of the legacy
methods defined by Vector. It also demonstrates the Enumeration interface.
// Demonstrate various Vector operations.
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
2007-09-19 02:47
Print this article
2 av 2
http://www.java-samples.com/forprinting.php?tutorialid=373
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
The output from this program is shown here:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
With the release of Java 2, Vector adds support for iterators. Instead of relying on an enumeration to cycle through the
objects (as the preceding program does), you now can use an iterator. For example, the following iterator-based code can
be substituted into the program:
// use an iterator to display contents
Iterator vItr = v.iterator();
System.out.println("\\nElements in vector:");
while(vItr.hasNext())
System.out.print(vItr.next() + " ");
System.out.println();
Because enumerations are not recommended for new code, you will usually use an iterator to enumerate the contents of a
vector. Of course, much legacy code exists that employs enumerations. Fortunately, enumerations and iterators work in
nearly the same manner.
COPYRIGHT© 2006 java-samples.com. ALL RIGHTS RESERVED.
2007-09-19 02:47