0% found this document useful (0 votes)
4 views32 pages

Collection Framework

The document provides an overview of the Java Collections Framework, detailing its various interfaces and classes such as Collection, List, Iterator, Comparator, Vector, Stack, Queue, and Map. It explains the methods associated with these interfaces and classes, highlighting their functionalities and differences, such as the distinction between Lists and Sets. Additionally, it includes code examples to illustrate the usage of these collections in Java programming.

Uploaded by

Zaid Z.Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views32 pages

Collection Framework

The document provides an overview of the Java Collections Framework, detailing its various interfaces and classes such as Collection, List, Iterator, Comparator, Vector, Stack, Queue, and Map. It explains the methods associated with these interfaces and classes, highlighting their functionalities and differences, such as the distinction between Lists and Sets. Additionally, it includes code examples to illustrate the usage of these collections in Java programming.

Uploaded by

Zaid Z.Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

 Looping

Outline
Collection
List Interface
Iterator
Comparator
Vector Class
Stack
Queue
List v/s Sets
Map Interfaces
Collection
• The Collection in Java is a framework that provides an
architecture to store and manipulate the group of objects.
• Java Collections can achieve all the operations that you perform
on a data such as searching, sorting, insertion, manipulation,
and deletion.
• Java Collection means a single unit of objects. Java Collection
framework provides many interfaces (Set, List, Queue, Deque)
and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).
Hierarchy of
Collection
Framework
Collection Interface - Methods
Sr. Method & Description
1 boolean add(E e)
It is used to insert an element in this collection.

2 boolean addAll(Collection<? extends E> c)


It is used to insert the specified collection elements in the invoking
collection.

3 void clear()
It removes the total number of elements from the collection.

4 booelan contains(Object element)


It is used to search an element.

5 boolean containsAll(Collection<?> c)
It is used to search the specified collection in the collection.

6 boolean equals(Object obj)


Returns true if invoking collection and obj are equal. Otherwise returns
false.

7 int hashCode()
Returns the hashcode for the invoking collection.
Collection Interface – Methods (Cont.)
Sr. Method & Description
8 boolean isEmpty()
Returns true if the invoking collection is empty. Otherwise returns
false.

9 Iterator iterator()
It returns an iterator.

10 boolean remove(Object obj)


Removes one instance of obj from the invoking collection. Returns
true if the element was removed. Otherwise, returns false.

11 boolean removeAll(Collection<?> c)
It is used to delete all the elements of the specified collection from
the invoking collection.

12 boolean retainAll(Collection<?> c)
It is used to delete all the elements of invoking collection except the
specified collection.

13 int size()
It returns the total number of elements in the collection.
List Interface
• The List interface extends Collection and 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 zero-based index.
• A list may contain duplicate elements.
• List is a generic interface with following declaration
interface List<E>
where E specifies the type of object.
List Interface - Methods
Sr. Method & Description
1 void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in index. Any
pre-existing elements at or beyond the point of insertion are shifted
up. Thus, no elements are overwritten.

2 boolean addAll(int index, Collection c)


Inserts all elements of c into the invoking list at the index passed in
index. Any pre-existing elements at or beyond the point of insertion
are shifted up. Thus, no elements are overwritten. Returns true if the
invoking list changes and returns false otherwise.

3 Object get(int index)


Returns the object stored at the specified index within the invoking
collection.

4 int indexOf(Object obj)


Returns the index of the first instance of obj in the invoking list. If obj
is not an element of the list, -1 is returned.

5 int lastIndexOf(Object obj)


Returns the index of the last instance of obj in the invoking list. If obj
is not an element of the list, -1 is returned.
List Interface – Methods (Cont.)
Sr. Method & Description
6 ListIterator listIterator( )
Returns an iterator to the start of the invoking list.

7 ListIterator listIterator(int index)


Returns an iterator to the invoking list that begins at the specified
index.

8 Object remove(int index)


Removes the element at position index from the invoking list and
returns the deleted element. The resulting list is compacted. That is,
the indexes of subsequent elements are decremented by one

9 Object set(int index, Object obj)


Assigns obj to the location specified by index within the invoking list.

10 List subList(int start, int end)


Returns a list that includes elements from start to end-1 in the
invoking list. Elements in the returned list are also referenced by the
invoking object.
List Interface (example)
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
List a1 = new ArrayList();
a1.add("Sachin"); Here ArrayList
a1.add("Sourav");
& LinkedList
a1.add("Shami");
System.out.println("ArrayList Elements"); implements
System.out.print("\t" + a1); List Interface

List l1 = new LinkedList();


l1.add("Mumbai");
l1.add("Kolkata");
l1.add("Vadodara");
System.out.println();
System.out.println("LinkedList Elements");
System.out.print("\t" + l1);
}
}
Iterator
• Iterator interface is used to cycle through elements in a collection,
eg. displaying elements.
• ListIterator extends Iterator to allow bidirectional traversal of
a list, and the modification of elements.
• Each of the collection classes provides an iterator( ) method that
returns an iterator to the start of the collection. By using this iterator
object, you can access each element in the collection, one element
at a time.
• To use an iterator to cycle through the contents of a collection, follow
these steps:
1. Obtain an iterator to the start of the collection by calling the collection's
iterator( ) method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as
long as hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
Iterator - Methods
Sr Method & Description
.
1 boolean hasNext()
Returns true if there are more elements. Otherwise, returns
false.
2 E next()
Returns the next element.
3 void remove()
Removes the current element. Throws IllegalStateException if
an attempt is made to call remove() that is not preceded by a
call to next()
Iterator - Example
import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
System.out.print("Contents of list: ");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
}
}
Comparator
• Comparator interface is used to set the sort order of the object
to store in the sets and lists.
• The Comparator interface defines two methods: compare( ) and
equals( ).
• int compare(Object obj1, Object obj2)
obj1 and obj2 are the objects to be compared. This method
returns zero if the objects are equal. It returns a positive value if
obj1 is greater than obj2. Otherwise, a negative value is
returned.
• boolean equals(Object obj)
obj is the object to be tested for equality. The method returns
true if obj and the invoking object are both Comparator objects
and use the same ordering. Otherwise, it returns false.
Comparator Example
class AgeComparator implements
Comparator<Object>{
public int compare(Object o1,Object
public class ComparatorDemo {
o2){
public static void main(String args[]){
Student s1=(Student)o1;
ArrayList<Student> al=new
Student s2=(Student)o2;
ArrayList<Student>();
if(s1.age==s2.age) return 0;
al.add(new Student("Vijay",23));
else if(s1.age>s2.age) return 1;
al.add(new Student("Ajay",27));
else return -1;
al.add(new Student("Jai",21));
}
System.out.println("Sorting by age");
}
Collections.sort(al,new AgeComparator()); import java.util.*;
Iterator<Student> itr2=al.iterator(); class Student {
while(itr2.hasNext()){ String name;
Student int age;
st=(Student)itr2.next(); Student(String name,
System.out.println(st.name+" int age){
"+st.age); this.name = name;
} this.age = age;
} }
} }
Vector Class
• 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 collection
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 is declared as follows:
Vector<E> = new Vector<E>;
Vector - Constructors
Sr Constructor & Description
.
Vector( )
This constructor creates a default vector, which has an initial
size of 10
Vector(int size)
This constructor accepts an argument that equals to the
required size, and creates a vector whose initial capacity is
specified by size:
Vector(int size, int incr)
This constructor creates a vector whose initial capacity is
specified by size and whose increment is specified by incr. The
increment specifies the number of elements to allocate each
time that a vector is resized upward
Vector(Collection c)
creates a vector that contains the elements of collection c
Vector - Methods
Sr Method & Description
.
boolean containsAll(Collection c)
Returns true if this Vector contains all of the elements in the
specified Collection.
Enumeration elements()
Returns an enumeration of the components of this vector.
Object firstElement()
Returns the first component (the item at index 0) of this
vector.
Object get(int index)
Returns the element at the specified position in this Vector.
int indexOf(Object elem)
Searches for the first occurence of the given argument, testing
for equality using the equals method.
boolean isEmpty()
Vector – Method (Cont.)
Sr Method & Description
.
Object lastElement()
Returns the last component of the vector.
int lastIndexOf(Object elem)
Returns the index of the last occurrence of the specified object
in this vector.
Object remove(int index)
Removes the element at the specified position in this Vector.
boolean removeAll(Collection c)
Removes from this Vector all of its elements that are
contained in the specified Collection.
Object set(int index, Object element)
Replaces the element at the specified position in this Vector
with the specified element.
int size()
Stack
• Stack is a subclass of Vector that implements a standard last-
in, first-out stack.
• Stack only defines the default constructor, which creates an
empty stack.
• Stack includes all the methods defined by Vector and adds
several of its own.
• Stack is declared as follows:
Stack<E> st = new Stack<E>();
where E specifies the type of object.
Stack - Methods
• Stack includes all the methods defined by Vector and adds
several methods of its own.
Sr. Method & Description

1 boolean empty()
Returns true if the stack is empty, and returns false if the stack
contains elements.

2 E peek()
Returns the element on the top of the stack, but does not remove
it.

3 E pop()
Returns the element on the top of the stack, removing it in the
process.

4 E push(E element)
Pushes element onto the stack. Element is also returned.

5 int search(Object element)


Searches for element in the stack. If found, its offset from the top
of the stack is returned. Otherwise, -1 is returned.
Queue
• Queue interface extends Collection and declares the
behaviour of a queue, which is often a first-in, first-out list.
• LinkedList and PriorityQueue are the two classes which
implements Queue interface
• Queue is declared as follows:
Queue<E> q = new LinkedList<E>();
Queue<E> q = new PriorityQueue<E>();
where E specifies the type of object.
Queue - Methods
Sr. Method & Description

1 E element()
Returns the element at the head of the queue. The element is not
removed. It throws NoSuchElementException if the queue is
empty.

2 boolean offer(E obj)


Attempts to add obj to the queue. Returns true if obj was added
and false otherwise.

3 E peek()
Returns the element at the head of the queue. It returns null if the
queue is empty. The element is not removed.

4 E poll()
Returns the element at the head of the queue, removing the
element in the process. It returns null if the queue is empty.

5 E remove()
Returns the element at the head of the queue, returning the
element in the process. It throws NoSuchElementException if the
queue is empty.
Queue Example
import java.util.*;
public class QueueDemo {
public static void main(String[] args) {
Queue<String> q = new LinkedList<String>();
q.add("Tom");
q.add("Jerry");
q.add("Mike");
q.add("Steve");
q.add("Harry");
System.out.println("Elements in Queue:"+q);
System.out.println("Removed element:
"+q.remove());
System.out.println("Head: "+q.element());
System.out.println("poll(): "+q.poll());
System.out.println("peek(): "+q.peek());
System.out.println("Elements in Queue:"+q);
}
}
PriorityQueue
• PriorityQueue extends AbstractQueue and implements the
Queue interface.
• It creates a queue that is prioritized based on the queue's
comparator.
• PriorityQueue is declared as follows:
PriorityQueue<E> = new PriorityQueue<E>;
• It builds an empty queue with starting capacity as 11.
PriorityQueue - Example
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> numbers = new
PriorityQueue<>();
numbers.add(750);
numbers.add(500);
numbers.add(900);
numbers.add(100);
while (!numbers.isEmpty()) {
System.out.println(numbers.remove());
}
}
}
List v/s Sets
List Set
Lists allow duplicates. Sets allow only unique
List is an ordered elements.
Sets is an unordered
collection.
Popular implementation of collection.
Popular implementation of
List interface includes Set interface includes
ArrayList, Vector and HashSet, TreeSet and
LinkedList. LinkedHashSet.
When to use List and Set?
Lists - If insertion order is maintained during insertion and allows
duplicates.
Sets – If unique collection without any duplicates without
maintaining order.
Maps
• A map is an object that stores associations between keys and
values, or key/value pairs.
• Given a key, you can find its value. Both keys and values are
objects.
• The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others
cannot.
• Maps don't implement the Iterable interface. This means that
you cannot cycle through a map using a for-each style for loop.
Furthermore, you can’t obtain an iterator to a map.
Map Interfaces
Interface Description
Map Maps unique keys to values.
Map.Entry Describes an element (a key/value
pair) in a map. This is an inner class
of Map.
NavigableMap Extends SortedMap to handle the
retrieval of entries based on closest-
match searches.
SortedMap Extends Map so that the keys are
maintained in ascending order.
Map Classes
Class Description
AbstractMap Implements most of the Map
interface.
EnumMap Extends AbstractMap for use with
enum keys.
HashMap Extends AbstractMap to use a hash
table.
TreeMap Extends AbstractMap to use a tree.
WeakHashMap Extends AbstractMap to use a hash
table with weak keys.
LinkedHashMap Extends HashMap to allow insertion-
order iterators.
IdentityHashMa Extends AbstractMap and uses
p reference equality when comparing
HashMap Class
• The HashMap class extends AbstractMap and implements the
Map interface.
• It uses a hash table to store the map. This allows the execution
time of get() and put() to remain constant even for large sets.
• HashMap is a generic class that has declaration:
class HashMap<K,V>
HashMap - Constructors
Sr Constructor & Description
.
1 HashMap()
Constructs an empty HashMap with the default initial capacity
(16) and the default load factor (0.75).
2 HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial
capacity and the default load factor (0.75).
3 HashMap(int initialCapacity, float loadFactor)
Constructs an empty HashMap with the specified initial
capacity and load factor.
4 HashMap(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the
specified Map.
import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map.
HashMap<String, Double> hm = new HashMap<String, Double>();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Tod Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries.
Set<Map.Entry<String, Double>> set = hm.entrySet();
// Display the set.
for(Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
//Deposit 1000 into John Doe's account.
double balance = hm.get("John Doe");
hm.put("John Doe", balance + 1000);
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}

You might also like