You are on page 1of 37

ArrayList & Vector in

detail
Objectives

• Array List
• Vector
1:Importing,
2:Declaration of vectors,
3:Adding elements to a vector,
4:Deleting elements in a vector,
5:Accessing an Element.
6:Discovering vector size,
7:Improving Efficiency.
ArrayList

• The ArrayList class extends AbstractList and implements the List


interface. ArrayList supports dynamic arrays that can grow as
needed.
• Standard Java arrays are of a fixed length. After arrays are created,
they cannot grow or shrink, which means that you must know in
advance how many elements an array will hold.
• Array lists are created with an initial size. When this size is
exceeded, the collection is automatically enlarged. When objects
are removed, the array may be shrunk
• The ArrayList class supports three constructors. The first constructor builds an
empty array list.:
• ArrayList( )

• The following constructor builds an array list that is initialized with the elements
of the collection c.
• ArrayList(Collection c)

• The following constructor builds an array list that has the specified initial
capacity. The capacity is the size of the underlying array that is used to store the
elements.

• The capacity grows automatically as elements are added to an array list.


• ArrayList(int capacity)
Apart from the methods inherited from its parent classes,
ArrayList defines following methods:
SN Methods with Description
1 void add(int index, Object element)
Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of
range (index < 0 || index > size()).
2 boolean add(Object o)
Appends the specified element to the end of this list.
3 boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's
iterator. Throws NullPointerException if the specified collection is null.
4 boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the
specified collection is null.
5 void clear()
Removes all of the elements from this list.
6 Object clone()
Returns a shallow copy of this ArrayList.
7 boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such
that (o==null ? e==null : o.equals(e)).
8 void ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the
minimum capacity argument.
9 Object get(int index)
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index <
0 || index >= size()).
10 int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
11 int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.

12 Object remove(int index)


Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >=
size()).

13 protected void removeRange(int fromIndex, int toIndex)


Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.

14 Object set(int index, Object element)


Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified
index is is out of range (index < 0 || index >= size()).

15 int size()
Returns the number of elements in this list.
16 Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.

17 Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the
specified array.

18 void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
The following program illustrates several of
the methods supported by ArrayList:
import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Activity Notebook
1.Three ArrayList constructors
2.Returns the number of elements in this list.
3.Inserts the specified element at the specified position index in
this list
4.Removes all of the elements from this list.
5.Inserts the specified element in the list
6.Removes the element at the specified position in this list.
7.Replaces the element at the specified position in this list with the
specified element.
Activity Notebook
1.Three ArrayList constructors
1. ArrayList( )
2. ArrayList(Collection c )
3. ArrayList( int capacity)
2. int size() Returns the number of elements in this list.
3. void add(int index, Object element) Inserts the specified element at the specified
position index in this list
4. void clear() Removes all of the elements from this list.
5. void add(Object element) Inserts the specified element in the list
6. Object remove(int index) Removes the element at the specified position in this list.

7. Object set(int index, Object element) Replaces the element at the specified position in
this list with the specified element.
Trace the output
first item
second item
third item
7
Whole list=[first item, third item, 7]
Position 1=third item
Exercise
Create a program that will be able to do the
following:
• Add element in the list
• Edit element in the list
• Remove element in the list
• Remove all element in the list
• Search element in the list
• View all elements in the list
Exercise

•Create a program that read words, sort


them, and print them using ArrayList.
Vector

• implements a dynamic array. It is similar to


ArrayList, but with two differences:
• Vector is synchronized.
• Vector contains many legacy methods that are not
part of the collections framework.
• Vector proves 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.
Vector

Vector(int size, int Vector(collection


Vector() Vector(int size) incr) e)
• creates a default • creates a vector • form creates a • creates a vector that
vector, which has an whose initial vector whose initial contains the
initial size of 10 capacity is specified capacity is specified elements of
by size by size and whose collection c
increment is
specified by incr. The
increment specifies
the number of
elements to allocate
each time that a
vector is resized
upward
Basic Methods:

• add(Object o): It adds the element in the end of the Vector


• size(): It gives the number of element in the vector.
• elementAt(int index): It returns the element at the specified index.
• firstElement(): It returns the first element of the vector.
• lastElement(): It returns last element.
• removeElementAt(int index): It deletes the element from the given index.
• elements(): It returns an enumeration of the element
1: Importing;

• import java.util.Vector;
• import java.util.Vector;
• import java.util.Vector;
2: Declaration of Vectors.
• Vector<String> myVector=new Vector<String>(10,2);
• This program declares a Vector of size 10 and its space will increase by 2 when more then
10 elements are added.

• If it was declared like below


• Vector<String> myVector=new Vector<String>();

• Then the starting size would be 10 by default and it would double everytime it became full

The control over how fast the array grows is used to ensure the vector never gets needlessly
big.

The "<String>" declares what variables the Vector can hold.
This can be replaced with other class type variables such as "<String>",
"<Double>",“<Integer>",“<Object>" and so on... but no primitive types like "int" ;
3: Adding to a vector

• Adding contents to a Vector can be done a number of


ways. The way I'll explain begins with declaring a vector
of Strings.
String str=“hello"; //test string declared
myVector.add(str); //adds sample's value to the vector
System.out.println(“The Value is :"+myVector.get(0));
4:Deleting Elements

• To delete an element in an array we use the


.remove() command

• myVector.remove(0); //this removes the element


at the specified position
5:Accessing an Element.

• holder=myVector.elementAt(0);
System.out.println("Value is :"+holder);
//Displays the value

• This program use's the elementAt() function to


extract the value from the array into a normal
variable and then display it.
The next program shows the .toString() function
import java.util.Vector; //imports vector utility
class example{
public static void main(String []args){
Vector<String> myVector=new Vector<String>(10,2); //declare vector
String e1="Element1Contense"; //this string will be later added to the
vector at 0
String e2="Element2Contense"; //this string will be later added to the
vector at 1
String holder; //this string will hold the values
extracted for the vector
myVector.add(e1); //adds e1 to the vector
myVector.add(e2); //adds e2 to the vector
holder=myVector.toString(); //holder becomes equal to all the elements in
the vector
System.out.println("Value is :"+holder); //Displays the value
}
}

The above program adds two elements to the vector then all the elements are extracted as one
string which is displayed to the screen.
6:Discovering vector size,

• Discovering the size of a vector is a


constant necessity as it increases and
decrease in size.
• This makes the demands on a loop in your
program change as the program runs the
.size() function
import java.util.Vector; //imports vector utility
class example{
public static void main(String []args){
Vector<String> myVector=new Vector<String>(10,2); //declare vector
String e1="Element1"; //this string will be later added to the vector at 0
String e2="Element2"; //this string will be later added to the vector at 1
int number; //this string will hold the values extracted for the
vector
myVector.add(e1); //adds e1 to the vector
myVector.add(e2); //adds e2 to the vector
number=myVector.size(); //number becomes equal to the number of elements in the vector
System.out.println("The Number of elements are :"+number); //Displays the value
}//end of main
}//end of class

• The Above program discovers the size of the vector. It would never really be used in the format that is shown
above.
• The real purpose of .size() is that it gives you control over loops that you can use in your programs as shown in
the next step.
7: Improving Efficiency:
import java.util.Vector; //imports vector utility
import java.util.Scanner; //imports scanner utility

class example{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
Vector<String> myVector=new Vector<String>(10,2); //declare vector
String word=""; //this string will be later added to the vector at 0
//Fill vector
for(int i=0;i<=myVector.size();i++){ //this for loop will run for eternity, unless
someone enters EXIT
System.out.print("\n Type EXIT to exit loop , Enter a word :");
word=scan.nextLine(); //reads in String from user
if(word.equals("EXIT")){ //causes loop to exit
break;
}
}
Apart from the methods inherited from its parent classes, Vector defines following
methods:
Methods with Description
1 void add(int index, Object element)
Inserts the specified element at the specified position in this Vector.
2 boolean add(Object o)
Appends the specified element to the end of this Vector.
3 boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified
Collection's Iterator.
4 boolean addAll(int index, Collection c)
Inserts all of the elements in in the specified Collection into this Vector at the specified position.

5 void addElement(Object obj)


Adds the specified component to the end of this vector, increasing its size by one.
6 int capacity()
Returns the current capacity of this vector.
7 void clear()
Removes all of the elements from this Vector.
8 Object clone()
Returns a clone of this vector.
9 boolean contains(Object elem)
Tests if the specified object is a component in this vector.
10 boolean containsAll(Collection c)
Returns true if this Vector contains all of the elements in the specified Collection.
11 void copyInto(Object[] anArray)
Copies the components of this vector into the specified array.
12 Object elementAt(int index)
Returns the component at the specified index.
13 Enumeration elements()
Returns an enumeration of the components of this vector.
14 void ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components
specified by the minimum capacity argument.

15 boolean equals(Object o)
Compares the specified Object with this Vector for equality.
16 Object firstElement()
Returns the first component (the item at index 0) of this vector.
17 Object get(int index)
Returns the element at the specified position in this Vector.
18 int hashCode()
Returns the hash code value for this Vector.
19 int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for equality using the equals method.

20 int indexOf(Object elem, int index)


Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the
equals method.
21 void insertElementAt(Object obj, int index)
Inserts the specified object as a component in this vector at the specified index.

22 boolean isEmpty()
Tests if this vector has no components.
23 Object lastElement()
Returns the last component of the vector.
24 int lastIndexOf(Object elem)
Returns the index of the last occurrence of the specified object in this vector.
25 int lastIndexOf(Object elem, int index)
Searches backwards for the specified object, starting from the specified index, and returns an index to it.

26 Object remove(int index)


Removes the element at the specified position in this Vector.
27 boolean remove(Object o)
Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is
unchanged.
28 boolean removeAll(Collection c)
Removes from this Vector all of its elements that are contained in the specified Collection.

29 void removeAllElements()
Removes all components from this vector and sets its size to zero.
30 boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this vector.
31 void removeElementAt(int index)
removeElementAt(int index)
32 protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
33 boolean retainAll(Collection c)
Retains only the elements in this Vector that are contained in the specified Collection.
34 Object set(int index, Object element)
Replaces the element at the specified position in this Vector with the specified element.
35 void setElementAt(Object obj, int index)
Sets the component at the specified index of this vector to be the specified object.

36 void setSize(int newSize)


Sets the size of this vector.
37 int size()
Returns the number of components in this vector.
38 List subList(int fromIndex, int toIndex)
Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
39 Object[] toArray()
Returns an array containing all of the elements in this Vector in the correct order.
40 Object[] toArray(Object[] a)
Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the
specified array.

41 String toString()
Returns a string representation of this Vector, containing the String representation of each element.
42 void trimToSize()
Trims the capacity of this vector to be the vector's current size.
• The following program illustrates several of the methods
supported by this collection:
import java.util.*;
public 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: " + 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(); } }
• Array vs ArrayList vs LinkedList vs Vector with very good overview and
examples.
• An ArrayList is ordered collection (also known as a sequence). It
means that the user of controls where each element is inserted. This
class is very similar to the Vector class, excepting that it is not
synchronized. It must be synchronized externally.
• An ArrayList is better than Array to use when you have no knowledge
in advance about elements number. ArrayList are slower than Arrays.
So, if you need efficiency try to use Arrays if possible.
• Short Overview on main features of ArrayList:
• - The add operation runs O(n) time.
• - The isEmpty, size, iterator, set, get and listIterator operations require the same
amount of time, independently of element you access.
• - Only Objects can be added to an ArrayList
• - Implements all methods from the List interface
• - Permits null elements
• An ArrayList could be a good choice if you need very
flexible Array type of collection with limited functionality.
Array

Venn Diagram • Fixed size


• Single type

LinkedList
• add and remove is Vector
better Data structure/
performance • Synchronized
list array • Double its array
• More methods Index=0
offer(0, size
peak(),poll()

Dynamic storage Dynamic storage

ArrayList
• Not Synchronized
• Thread-safe
• Resizable upto 50%
• It’s size increase dynamically
• Worse Get and set methods
Vector is a broken class that is not threadsafe, despite it being
"synchronized" and is only used by students and other inexperienced
programmers.

ArrayList is the go-to List implementation used by professionals and


experienced programmers.

Professionals wanting a threadsafe List implementation use


a CopyOnWriteArrayList.

1. Arraylist is not synchronized while vector is.


2. Arraylist has no default size while vector has a default size of 10.
3. Arraylist don't define any increment size while vector does.
4. Arraylist can be seen directly without any iterator while vector requires
an iterator to display all it's content.
• Use ArrayLists if there is no specific requirement to use Vectors.

• Synchronization

• If multiple threads access an ArrayList concurrently then we must externally


synchronize the block of code which modifies the list either structurally or simply
modifies an element. Structural modification means addition or deletion of element(s)
from the list. Setting the value of an existing element is not a structural modification.
• Collections.synchronizedList is normally used at the time of creation of the list to
avoid any accidental unsynchronized access to the list.

• Data growth

• Internally, both the ArrayList and Vector hold onto their contents using an Array.
When an element is inserted into an ArrayList or a Vector, the object will need to
expand its internal array if it runs out of room. A Vector defaults to doubling the
size of its array, while the ArrayList increases its array size by 50 percent.
Laboratory Exercise-Vector (100pts)

• Create a program that will be able to do the following (String


object):
• Add element in the list
• Edit element in the list
• Remove element in the list
• Remove all element in the list
• Search element in the list
• View all elements in the list
• Seek for duplicate values
• Sort the element using selection sort

You might also like