Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Java Collections Api

Architecture

A collection is simply an object that groups multiple elements into a single unit. It is also called
as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data
List

 a List is a collection whose elements can be accessed by an index


 the indices are zero-based
 a list can contain duplicate elements
 a List provides a special ListIterator which allows you to move backwards and forwards
through the elements
List Methods
Methods Usage
add() Adds an  objects to the collection

clear() Removes all objects from the collection.

contains() Returns true if a special object is an element with in the


collection.

get() Returns the element at the specified index position in this


collection.

isEmpty() Returns true if the collection has no elements.

listIterator() Returns a ListItertor object for the collection which may then be
used to retrieve an object.

Remove() Removes the element at the specified index position in this


collection.

size() Returns the number of elements in the collection.

List Implementations

List listA = new ArrayList();

List listB = new LinkedList();

List listC = new Vector();

List listD = new Stack();


ArrayList

 The Array List class is a concrete implementation of List interface. This class supports
dynamic arrays that can grow as needed.
 In java, standard arrays are of fixed length. After arrays are created, they cannot grow or
shrink, which means you must know in advance how many elements an array will hold.
 For example, storing information about the days of the week should use an array because
the number of days in a week is constant. Use an array list for your email contact list
because there is no upper bound on the number of contacts
 An object of this can dynamically increase or decrease in size.
 An ArrayList can be traversed using a foreach loop, iterators, or indexes.
Example 1
Example 2
Vector

It is similar to Array List, but with two differences:  Vector is synchronized, and it contains
many legacy methods that are not part of the collections framework

Performance Issues

1. Capacity

Vector vector = new Vector();

Newly created vector has no element in it so its size is 0 but its capacity is 10 by default. So if you
don’t specify the capacity of the vector (and call the default constructor), its capacity will be 10.
Capacity of the vector is the maximum amount of objects a vector can hold before extension.

Vector expansion is an expensive operation. A larger array is created, contents of old array are
moved on to newly created array and then the old array is gets reclaimed by garbage collector. So,
the programmer should try to reduce Vector expansion scenarios if elimination is not possible.

Vector vector = new Vector(100);

In the example above, we created a Vector with initial capacity of 100. Here we have not specified
the expansion/growth factor. By default, the Vector’s capacity will double with every expansion.

Vector vector = new Vector(100,25);

This is another way of declaring Vector. Here vector has initial capacity of 100 and will grow capacity
by increments of 25 elements per expansion.

Talking about performance, initial capacity and growth factor are very important. One should try to
minimize the need for expansion. Its an ideal scenario, that no expansion is required but one should
also not declare a vector of initial capacity too large as compared to usage. For instance if you know
that a vector will contain from 100 to 200 objects, then declaring a vector of 1000 capacity is not
good at all.

So the conclusion is, do proper study and come up with proper and realistic estimates before
declaring vectors. These things are usually ignored but they do make a difference
2. Elements Insertion

Adding elements to a Vector is a normal practice but there are few performance issues related to
this which should be considered.

Elements can be added to Vector using any of the following:

- insertElementAt(e, index)
- addElement(e)
- add(e)
- add(index,e)

The addElement(e) and add(e) methods are used to add elements at the end of Vector whereas
insertElementAt(e, index) and add(index, e) methods are used to insert element at any index of the
Vector.

Vector <String>vec = new Vector<String>();


 
vec.add("String1");
vec.add("String2");
 
vec.addElement("String3");
vec.addElement("String4");
 
vec.add(0, "String5");
vec.add(1, "String6");
 
vec.insertElementAt("String7", 1);
vec.insertElementAt("String8", 0);
 
for(String s:vec)
{
System.out.println(s);
}

Output:

String8
String5
String7
String6
String1
String2
String3
String4
Thing to note is that vector stores elements in continuous memory locations. Now if you add
element at the end of Vector, then no shift is required for other elements. But if you add an element
at some other place, shift operation is required. For example, if a Vector has 9 elements and you
plan to add an element at the 1st place (0th index), then 9 shifts are required, which is a costly
operation. And if you add it at the end of the Vector, then there is no shift required.

So, use insertElementAt(e, index) or add(index,e) if really required.

ArrayList Vs Vector

 ArrayList is faster than Vector except when there is no lock acquisition required in HotSpot
JVMs (when they have about the same performance).
 Vector and ArrayList implementations have excellent performance for indexed access and
update of elements, since there is no overhead beyond range checking.
 Adding elements to, or deleting elements from the end of a Vector or ArrayList also gives
excellent performance except when the capacity is exhausted and the internal array has to
be expanded.
 Inserting and deleting elements to Vectors and ArrayLists always require an array copy (two
copies when the internal array must be grown first). The number of elements to be copied is
proportional to [size-index], i.e. to the distance between the insertion/deletion index and
the last index in the collection. The array copying overhead grows significantly as the size of
the collection increases, because the number of elements that need to be copied with each
insertion increases.
 For insertions to Vectors and ArrayLists, inserting to the front of the collection (index 0)
gives the worst performance, inserting at the end of the collection (after the last element)
gives the best performance.
 LinkedLists have a performance overhead for indexed access and update of elements, since
access to any index requires you to traverse multiple nodes.
 LinkedList insertions/deletion overhead is dependent on the how far away the
insertion/deletion index is from the closer end of the collection.
 Synchronized wrappers (obtained from Collections.synchronizedList(List)) add a level of
indirection which can have a high performance cost.
 Only List and Map have efficient thread-safe implementations: the Vector and Hashtable
classes respectively.
 List insertion speed is critically dependent on the size of the collection and the position
where the element is to be inserted.
 For small collections ArrayList and LinkedList are close in performance, though ArrayList is
generally the faster of the two. Precise speed comparisons depend on the JVM and the
index where the object is being added.
 Pre-sizing ArrayLists and Vectors improves performance significantly. LinkedLists cannot be
pre-sized.
 ArrayLists can generate far fewer objects for the garbage collector to reclaim, compared to
LinkedLists.
 For medium to large sized Lists, the location where elements are to inserted is critical to the
performance of the list. ArrayLists have the edge for random access.
 A dedicated List implementation designed to match data, collection types and data
manipulation algorithms will always provide the best performance.
 ArrayList internal node traversal from the start to the end of the collection is significantly
faster than LinkedList traversal. Consequently queries implemented in the class can be
faster.
 Iterator traversal of all elements is faster for ArrayList compared to Linkedlist.

You might also like