[go: up one dir, main page]

0% found this document useful (0 votes)
41 views11 pages

Vector: Vector Transactions New Vector

Vector defines a sequence of elements that can grow automatically. It works like an array but can dynamically increase capacity. It holds object references, not actual objects. You can initialize a Vector with an initial capacity and specify how capacity increases when exceeded. You can add, insert, get, set, and remove elements. Common operations include ensuring capacity, changing size, storing/retrieving objects, and extracting elements into an array.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views11 pages

Vector: Vector Transactions New Vector

Vector defines a sequence of elements that can grow automatically. It works like an array but can dynamically increase capacity. It holds object references, not actual objects. You can initialize a Vector with an initial capacity and specify how capacity increases when exceeded. You can add, insert, get, set, and remove elements. Common operations include ensuring capacity, changing size, storing/retrieving objects, and extracting elements into an array.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

 Vector<T>

 Defines a sequence or collection of


elements of any type T.
 Works like an array
 Can grow itself automatically when more
capacity is needed.
 Like arrays, vectors hold object references
only, not actual objects.
Creates an empty
Vector<String> transactions = new Vector<String>();
vector with a capacity
for 10 String objects.

 100 strings initially.


Vector<String> transactions = new Vector<String>(100);
Capacity
 is
doubled each time
current capacity is
Why not increment the vector object by 1 each
exceeded.
time then? The reason is that the process Initial capacity
of
of 100.
incrementing the capacity takes time  because
Capacity it
Vector<String> transactions
involves copying the =contents
new Vector<String>(100,10);
to a newincreases
area ofby
memory. The bigger the vector is, the longer 10 elementsthe
each time
copy takes, and that will affect your program’s
more space is
performance if it happens very often. required.
Example-1 [Using a

TrySimpleVecto
r.java

The Capacity and Size of a


Obtaining and Ensuring

int namesMax = names.capacity(); // Get current capacity


names.ensureCapacity(150); // Set minimum capacity to
150
 Capacity < 150  capacity increases to that
value.
 Capacity ≥ 150  capacity unchanged.
Changing the

int freeCount = names.capacity() – names.size(); //number of


names.setSize(50); // Set sizeSize
to can be increased /
50
 If size < 50  additional elements up to 50 will be filled with
null references.
 Size > 50  all object references in excess of 50 will be

discarded. The objects themselves may still be available if


other references to them exist.

names.trimToSize(); // Set capacity to  Changes capacity


to match current
size
Changing the

Storing Objects in a
 Adds a reference to the object aName to
transactions.add(aName);
the Vector<> object called names.
 New entry is added at the end of the
existing objects in the vector.
 Vector size increases by 1.
 All objects already stored in the vector
remain at their previous index position.

names.add(2, aName);
Inserts object aName as the 3rd entry of names

 Returns
names.set(2, newName);
a reference to the object that was previously stored
at this position. This gives us a chance to hang on to the
displaced object if we want to keep it.
 Changes the 3rd element in the Vector object from names to
newName.
st
 If the 1 argument is -ve, or is greater than or equal to the
current size of the Vector, the method will throw an
ArrayIndexOutOfBoundsException.

Appends all the objects from another


names.addAll(myNamesList)
collection myNamesList to the Vector object
; names.
names.addAll(i, Inserts the objects from myNamesList
starting at index position i
myNamesList);
Retrieving Objects from a

String name=Retrieves
th
the 5 vector element in the vector.
names.get(4);
 Return type for get() is determined by the type argument
used to create the Vector<> object.
 Throws an exception of type
ArrayIndexOutOfBoundsException if the argument is an
illegal index value. The index must be non-negative and
less than the size of the vector.

String name = names.firstElement();


Retrieves the 1st element in the Vector names.

Accessing Elements in a Vector through a List


 We can obtain a ListIterator reference from a
vector by calling listIterator().
ListIterator<String> listIter = names.listIterator();

ListIterator<String> listIter = names.listIterator(2);


 Results in a list iterator that encapsulates the elements from
names from the element at index position 2 to the end.
 Argument must not be -ve and must be less than the size of
names; otherwise, an IndexOutOfBoundsException will be thrown.
List<String> list = names.subList(2, 5); //Extract elements 2 to

ListIterator<String> listIter = names.subList(5,


 The call to subList() returns a List<String> object that encapsulates the elements
from names at index positions 5 to 14, inclusive. We then call listIterator() for this
List<String> object, which will return a list iterator of type ListIterator<String> for
elements in the list from index position 2 to the end in the List<String> collection.
This corresponds to elements 7 to 14, inclusive, from the original names vector.

Extracting All the Elements from a

String[ ] data = names.toArray(new String[names.size()]);


 The argument to toArray() must be an array of the same type or a supertype of the
type of elements in the vector. If it isn’t, an exception of type ArrayStoreException
will be thrown.
 If the argument is null, then an exception of type NullPointerException will be
thrown.
 If the array passed as the argument is not large enough to accommodate all the
elements in the vector, then a new array will be created, and a reference to that will
be returned.
 toArray() here returns an array of type String[ ] containing all the elements from
names in the correct sequence.
 The java.util.Arrays class defines a static
parameterized method, asList(), that will
convert an array of a given type, T, into a
List<T> collection.
String[ ] people = { “Brian”, “Beryl”, “Belinda”, “Barry”, “Bill”,
“Barbara” };
List<String> nameList = java.util.Arrays.asList(people);
Note that the List<> reference that is returned does not have storage
independent of the array. The List<> object is backed by the array passed as
the argument.

Since a List<String> reference is also a


Collection<String> reference:-
Vector<String> names =
new

Removing Objects from a

String name = names.remove(3);


Removes the 4th reference from names.
 Searches the names
boolean deleted = names.remove(aName); vector from
the beginning to find the 1st
reference to the object aName and
remove it.
 If the object is found and removed
from the vector, the method returns
true; otherwise, it returns false.
boolean deleted = Element
names.removeElementAt(2); at index
position 2 will be

Removes elements 5
names.removeAll(names.subList(5,15)); to 14, inclusive,
from the Vector<String> object names,
plus any duplicates of those objects that
are in the vector.

 Keeps the elements at index positions 5


names.retainAll(names.subList(5,15));
to 14, inclusive, and discards the rest.
 Rreturns true if the vector has been
changed (if at least 1 element has been
removed as a result of the operation).
 Throw an exception of type
NullPointerException if the argument is
null.

 Removes all the


transactions.removeAllElements(); // Dump the whole
elements and
lot
sets the size to
transactions.isEmpty(); // Returns true zero.
Note that a Vector<> object may contain only null
references, but this doesn’t mean the size() will be zero
or that the isEmpty() method will return true. To empty a
Vector<> object you must actually remove the elements,

Searching a

 Returns the index


int position = names.indexOf(aName); position of an object
aName stored in the vector names.
 Searches the names vector from the
beginning for the object aName using the
equals() method for the argument. So
aName class type needs to have a proper
implementation of equals() for this to work.
 The variable position will contain either the
index of the 1st reference to the object in
transactions or -1 if the object isn’t found.

 Another available version of indexOf() accepts


a 2nd argument specifying the index position
where the search for the object should begin.
The main use for this arises when an object
can be referenced more than once in a vector.
This method can be used in situation to
recover all occurrences of any particular
object.
String aName = “Fred”; // Name to be found
int count = 0; // Number of occurrences
int position = -1; // Search starting index
while (++position<names.size()) { // Search with a valid index
if (position = names.indexOf(aName, position))<0) { // Find
next
 Counts the number of occurrences of a given
break; name in the names vector.
}  The while loop will continue as long as indexOf()
returns a valid index value and the index isn’t
++count; incremented beyond the end of the vector names.
}
Example-2 [Creating the
crowd]
TryVector.
java

You might also like