Today we have chosen a simple-but-no-least topic due to the common use of all of these classes and the utilities they provide us when manipulating sets of items.
First of all, we are going to initialize an array of String, whose size is determined at the moment of creation. To avoid this 'problem' we have some other collections.
Two of them are ArrayList and Vector. An ArrayList is an implementation of List, which is a collection that admits duplicated and null elements, as well as indexed access and some other methods to handle its elements. Vector class also inherits from List and behaves almost like ArrayList with some differences: Vector is 'thread safe' which means that if we intend to modify a Vector from two different threads, it will throw an exception. It is also called a syncronized class. This advantage implies a small handicap when talking about performance.
Before giving an example, I would like to recall that since version 1.5 of Java, if I am right, generic collections were introduced, and that involves an improvement as they support compile-time type checking. To define the type of the collection used, simply add 'less than' and 'greater than' simbols: '<' & '>' (e.g. Vector
Now, it is time for an example:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
public class Test1 {
public static void main(String[] args) {
String[] arrayString = new String[]{"1", "2", "3", "4"};
for (int i = 0; i < arrayString.length; i++) {
System.out.println(arrayString[i]);
}
ArrayList<String> arrayList = new ArrayList<String>(arrayString.length);
for (int i = 0; i < arrayString.length; i++) {
arrayList.add(arrayString[i]);
}
Iterator it = arrayList.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
Vector<String> vector = new Vector<String>(arrayString.length);
for (int i = 0; i < arrayString.length; i++) {
vector.add(arrayString[i]);
}
it = vector.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}