You are on page 1of 30

Collections Framework

Ashwaq El-shair

The Java 2 platform includes a collections


framework.
A collection is an object that represents a group
of objects.
A collections framework is a unified architecture
for representing and manipulating collections,
allowing them to be manipulated independently
of the details of their representation.

advantages of a collections
framework
Reduces programming effort by
providing useful data structures and
algorithms so you don't have to write
them yourself.
Increases performance by
providing high-performance
implementations of useful data
structures and algorithms.

advantages of a collections
framework ,cont.
Provides interoperability between
unrelated APIs by establishing a common
language to pass collections back and forth.
Reduces the effort required to learn APIs
by eliminating the need to learn multiple ad hoc
collection APIs.
Reduces the effort required to design and
implement APIs by eliminating the need to
produce ad hoc collections APIs.
Fosters software reuse by providing a
standard interface for collections and algorithms
to manipulate them.

The collections framework consists of:


Collection Interfaces - Represent different
types of collections, such as sets, lists and
maps. These interfaces form the basis of the
framework.
Interfaces allow collections to be manipulated
independently of the details of their representation

General-purpose Implementations - Primary


implementations of the collection interfaces.
Legacy Implementations - The collection
classes from earlier releases, Vector and
Hashtable, have been retrofitted to implement
the collection interfaces.

Collection Interfaces
The most basic interface is Collection.
These interfaces extend Collection:
Set, List, SortedSet, NavigableSet, Queue,
Deque, BlockingQueue and BlockingDeque.
The other collection interfaces, Map,
SortedMap, NavigableMap, ConcurrentMap
and ConcurrentNavigableMap do not extend
Collection, as they represent mappings
rather than true collections.

The Collection Interfaces:


The Collection Interface
This enables you to work with groups of
objects; it is at the top of the collections
hierarchy.
The Collection interface is the foundation
upon which the collections framework is built.
It declares the core methods that all
collections will have.
methods :
http://
www.tutorialspoint.com/java/java_collection_inter
face.htm

The Collection Interfaces, cont.


The List Interface
This extends Collection and an
instance of List stores an ordered
collection of elements.
declares the behavior of a collection
that stores a sequence of elements.
Elements can be inserted or accessed
by their position in the list, using a zerobased index.
A list may contain duplicate elements.

The Collection Interfaces, cont.


The Set
This extends Collection to handle sets,
which must contain unique elements.
cannot contain duplicate elements. It
models the mathematical set abstraction.
The Set interface contains only methods
inherited from Collection and adds the
restriction that duplicate elements are
prohibited.

The Collection Interfaces, cont.


The Map
This maps unique keys to values.
The Map interface maps unique keys to values. A key is
an object that you use to retrieve a value at a later date.
Given a key and a value, you can store the value in a Map
object. After the value is stored, you can retrieve it by
using its key.
Several methods throw a NoSuchElementException when
no items exist in the invoking map.
A ClassCastException is thrown when an object is
incompatible with the elements in a map.
A NullPointerException is thrown if an attempt is made to
use a null object and null is not allowed in the map.
An UnsupportedOperationException is thrown when an
attempt is made to change an unmodifiable map.

Difference between HashMap andWeakHashMap?

WeakHashMapis an implementation of Map interface


where the memory of the value object can be
reclaimed by Grabage Collector if the corresponding
key is no longer referred by any section of program.
This is different from HashMap where the value object
remain in HashMap even if key is no longer referred.
We need to explicitly call remove() method on
HashMap object to remove the value so that it can be
ready to be reclaimed(Provided no other section of
program refers to that value object). Calling remove()
is an extra overhead.

Collection Implementations

ArrayList
ArraylistisaclasswhichimplementsListinterfaceand
extendsAbstractListclass.
Theclassjava.util.ArrayListprovidesresizablearray,which
meansthatitemscanbeaddedandremovedfromthelist.
Itiswidelyusedbecauseofthefunctionalityandflexibilityit
offers.
MostofthedeveloperschooseArraylistoverArrayasitsa
verygoodalternativeoftraditionaljavaarrays.
AnArrayListisadynamicdatastructuresoitcanbeused
whenthereisnoupperboundonthenumberofelements.

DifferencebetweenArrayandArrayList
1. Resizable :
Array

Static in size -> fixed length data structure


One can not change the length after creating the
Array object.

ArrayList

Dynamic in size .
Each ArrayList object has instance variable
capacity which indicates the size of the ArrayList.
As elements are added to an ArrayList its capacity
grows automatically.

2.Primitives
Array

Can contain both primitive data types as well as


objects.

ArrayList

ArrayList can not contains primitive data types


(like int , float , double) it can only contains Object.
One get a misconception that we can store
primitives(int,float,double) in ArrayList , but it is
not true

Suppose we have ArrayList object ,


ArrayList arraylistobject = new ArrayList();
arraylistobject.add(23); // try to add 23
(primitive)
JVM through Autoboxing(converting primitives to
equivalent objects internally) ensures that only
objects are added to the arraylist object.
thus , above step internally works like this :
arraylistobject.add( new Integer(23));
// Converted int primitive to Integer object and
added to arraylistobject

3. Length
Array
Each array object has the length variable which
returns the length of the array.

Arraylist
Length of the ArrayList is provided by the size()
method.

4. Addingelements
Array

Using assignment operator.

ArrayList

Using add() method

5. Multidimensional
Array

Can be multi dimensional.

ArrayList

Single dimensional

ArrayList Constructors
TheArrayListclasssupportsthreeconstructors:
1. Arraylist()

Thisconstructorbuildsanemptylist.

2. ArrayList(Collection c)

Thisconstructorbuildsanarraylistthatisinitializedwiththe
elementsofthecollectionc.

3. ArrayList(int capacity)
Thisconstructorbuildsanarraylistthathasthespecifiedinitial
capacity.Thecapacityisthesizeoftheunderlyingarraythatisusedto
storetheelements.Thecapacitygrowsautomaticallyaselementsare
addedtoanarraylist.

Forexample,ifyouwanttocreateanemptyarraylistof
Stringsthenyouwoulddothefollowing:
ArrayList<String>list=newArrayList<String>();
Ifyouwanttocreateanarraylistwithinitialcapacity,then
youshoulddothefollowing:
ArrayList<Integer>list=newArrayList<Integer>(7);
NotethatArrayListclasssupportsonlyobjecttypesand
notprimitivetypes.

ArrayList common methods


Addingelementstothelist
booleanadd(Elemente)

Addsthespecifiedelementtotheendofthislist.

voidadd(intindex,Elemente)

Addsthespecifiedelementatthespecifiedpositioninthelist.

Removingelementsfromthelist
voidclear()

Removesalltheelementsfromthelist.

Eremove(intindex)

Removestheelementatthespecifiedpositioninthelist.

protectedvoidremoveRange(intstart,intend)
Removesfromthelistalltheelementsstartingfromindexstart
(included)untilindexend(notincluded).

Gettingelementsfromthelist
Eget(intindex)

Returnstheelementatthespecifiedposition.

Object[]toArray()

Returnsanarraycontainingalltheelementsofthelistinproper
sequence.

Settinganelement
Eset(intindex,Eelement)

Replacestheelementatthespecifiedpositionwiththespecified
element.

Searchingelements
booleancontains(Objecto)

Returnstrueifthespecifiedelementisfoundinthelist.

intindexOf(Objecto)

Returnstheindexofthefirstoccurrenceofthespecifiedelementinthe
list.Ifthiselementisnotinthelist,themethodreturns1.

intlastIndexOf(Objecto)

Returnstheindexofthelastoccurrenceofthespecifiedelementinthe
list.Ifthiselementisnotinthelist,themethodreturns1.

Iteratingthearraylist
Iteratoriterator()

Returnsaniteratorovertheelementsinthelist.

ListIteratorlistIterator()

Returnsalistiteratorovertheelementsinthislist.

Checkingifthelistisempty
booleanisEmpty()

Returnstrueifthelistdoesnotcontainanyelement .

Gettingthesizeofthelist
intsize()

Returnsthelengthofthelist(thenumberofelementscontainedinthe
list).

You might also like