Showing posts with label Vector. Show all posts
Showing posts with label Vector. Show all posts

Thursday, 19 May 2011

Introduction to Vectors in java

Vectors (the java.util.Vector class) are commonly used instead of arrays, because they expand automatically when new data is added to them. The Java 2 Collections API introduced the similar ArrayList data structure. ArrayLists are unsynchronized and therefore faster than Vectors, but less secure in a multithreaded environment. The Vector class was changed in Java 2 to add the additional methods supported by ArrayList. See below for a reasons to use each. The description below is for the (new) Vector class.
Vectors can hold only Objects and not primitive types (eg, int). If you want to put a primitive type in a Vector, put it inside an object (eg, to save an integer value use the Integer class or define your own class). If you use the Integer wrapper, you will not be able to change the integer value, so it is sometimes useful to define your own class.

Operating on Vectors in java–Common Operations

To Create a Vector

You must import either import java.util.Vector; or import java.util.*;. Vectors are implemented with an array, and when that array is full and an additional element is added, a new array must be allocated. Because it takes time to create a bigger array and copy the elements from the old array to the new array, it is a little faster to create a Vector with a size that it will commonly be when full. Of course, if you knew the final size, you could simply use an array. However, for non-critical sections of code programmers typically don't specify an initial size.
  • Create a Vector with default initial size
    Vector v = new Vector();
  • Create a Vector with an initial size
    Vector v = new Vector(300);

 

 

To Add elements to the end of a Vector

v.add(s); // adds s to the end of the Vector v

Iterating over elements of a Vector API of java

You can use a for loop to get all the elements from a Vector, but another very common way to go over all elements in a Vector is to use a ListIterator. The advantage of an iterator is that it it can be used with other data structures, so that if you later change to using a linked list for example, you won't have to change your code. Here is an example of using an iterator to print all elements (Strings) in a vector. The two most useful methods are hasNext(), which returns true if there are more elements, and next(), which returns the next element.
ListIterator iter = v.listIterator();
while (iter.hasNext()) {
System.out.println((String)iter.next());
}

Common methods in Vector API of Java

There are many useful methods in the Vector class and its parent classes. Here are some of the most useful. v is a Vector, i is an int index, o is an Object.
Method Description
v.add(o) adds Object o to Vector v
v.add(i, o) Inserts Object o at index i, shifting elements up as necessary.
v.clear() removes all elements from Vector v
v.contains(o) Returns true if Vector v contains Object o
v.firstElement(i) Returns the first element.
v.get(i) Returns the object at int index i.
v.lastElement(i) Returns the last element.
v.listIterator() Returns a ListIterator that can be used to go over the Vector. This is a useful alternative to the for loop.
v.remove(i) Removes the element at position i, and shifts all following elements down.
v.set(i,o) Sets the element at index i to o.
v.size() Returns the number of elements in Vector v.
v.toArray(Object[]) The array parameter can be any Object subclass (eg, String). This returns the vector values in that array (or a larger array if necessary). This is useful when you need the generality of a Vector for input, but need the speed of arrays when processing the data.

Replacements for old methods in Vector API

The following methods have been changed from the old to the new Vector API.
Old Method New Method
void addElement(Object) boolean add(Object)
void copyInto(Object[]) Object[] toArray()
Object elementAt(int) Object get(int)
Enumeration elements() Iterator iterator()
ListIterator listIterator()
void insertElementAt(Object, int) void add(index, Object)
void removeAllElements() void clear()
boolean removeElement(Object) boolean remove(Object)
void removeElementAt(int) void remove(int)
void setElementAt(int) Object set(int, Object)

See here for ensuring use of new method API in java.

Ensuring use of the new Vector API methods

When the new Collections API was introduced in Java 2 to provide uniform data structure classes, the Vector class was updated to implement the List interface. Use the List methods because they are common to other data structure. If you later decide to use something other than a Vector (eg, ArrayList, or LinkedList, your other code will not need to change.
Even up thru the first several versions of Java 2 (SDK 1.4), the language had not entirely changed to use the new Collections methods. For example, the DefaultListModel still uses the old methods, so if you are using a JList, you will need to use the old method names. There are hints that they plan to change this, but still and interesting omission.

When you create a Vector, you can assign it to a List (a Collections interface). This will guarantee that only the List methods are called.

Vector v1 = new Vector();  // allows old or new methods.
List v2 = new Vector(); // allows only the new (List) methods.

See here for replacements of old methods in Vector API.

Saturday, 14 May 2011

Difference between Enumeration and Iterator interface or Enumeration vs Iterator

Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:

Enumeration Iterator
Enumeration contains 2 methods namely hasMoreElements() & nextElement(). Iterator contains three methods namely hasNext(), next(),remove().
No such operation supported. It acts as read-only interface, as delete not supported. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects.
Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.

Difference between Vector and ArrayList? What is the Vector class OR ArrayList vs Vector

Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Both the classes are member of Java collection framework, therefore from an API perspective, these two classes are very similar. However, there are still some major differences between the two. Below are some key differences :

Vector ArrayList

Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2

Introduced in java v1.4.2. So its newer API.
Vector is synchronized. ArrayList is not.
Note: Even though Vector class is synchronized, still when you want programs to run in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.
Vector has default size. ArrayList has no default size.
The Enumerations returned by Vector's elements method are not fail-fast. Whereas ArrayList does not have any method returning Enumerations, like other new collections.

Thursday, 23 September 2010

List comparing to vector

Comparison to Vector

If you've used Vector(in the API reference documentation), you're already familiar with the general flavor of List. (Of course, List is an interface, while Vector is a concrete implementation.) List fixes several minor API deficiencies in Vector. For starters, commonly used Vector operations such as elementAt and setElementAt have been given much shorter names. When you consider that these two operations are the List analogue of square brackets for arrays, it becomes apparent that shorter names are highly desirable. Consider the following assignment statement:
a[i] = a[j].times(a[k]);
The Vector equivalent is:
v.setElementAt(v.elementAt(j).times(v.elementAt(k)), i);
The List equivalent is:
v.set(i, v.get(j).times(v.get(k)));
You may already have noticed that the set method, which replaces setElementAt, reverses the order of the arguments so that they match the corresponding array operation. Consider this assignment statement:
beatle[5] = "Billy Preston";
The Vector equivalent is:
beatle.setElementAt("Billy Preston", 5);
The List equivalent is:
beatle.set(5, "Billy Preston");
For consistency's sake, the add(int, Object) method, which replaces insertElementAt(Object, int), also reverses the order of the arguments. The various range operations in Vector (indexOf, lastIndexOf(setSize) have been replaced by a single range-view operation (subList), which is far more powerful and consistent.