Week 4.0 - ArrayListVector PDF
Week 4.0 - ArrayListVector PDF
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 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.
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
• 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.
• 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
• holder=myVector.elementAt(0);
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,
• 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.
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.
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.
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.
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
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()
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.
• Synchronization
• 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)