Unit 6 Collection
Unit 6 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).
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.Some of the methods of Collection interface are Boolean add ( Object
obj), Boolean addAll ( Collection c), void clear(), etc. which are implemented by all the
subclasses of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
1. boolean add(Object o):
It adds an element of Specific Object type at the end of Arraylist as no index is
mentioned in the method.
It returns True if element is successfully added, and returns false if it is not.
2. void add(int index, Object element):
It adds an element of Specific Object type at the specified index of the Arraylist
as given in the argument of the method.
It does not return anything as its return type is void.
If in case the index specified is out of range it throws
an IndexOutOfBoundsException.
3. boolean addAll(Collection c):
This method adds each element of the Specific collection type at the end of the
arraylist.
It returns True if collection is successfully added, and returns false if it is not.
If the collection passed in as an argument is null then it throws Null Pointer
Exception
4. boolean addAll(int index, Collection c):
This methods add each element of the Specific collection type at the specified index
as mentioned in the argument.
It returns true if collection is successfully added, and returns false if it is not.
If the collection passed in as an argument is null then it throws Null Pointer
Exception.The program of this method is:
5. void clear():
This method remove all the elements of the arraylist.
6. Object clone():
This method returns the exact same copy of the arraylist object.
7. boolean contains(Object element):
This method returns true if the calling arraylist object contains the specific element
as given in the argument list, otherwise it returns false.
12. Object remove(int index):
It deletes the element from the given index from the arraylist.
It returns an Exception IndexOutOfBoundsException, If index specified is out of range.
13.protected void removeRange(int first, int last):
It deletes the group of elements from the first to last as mentioned in the argument.
It includes the first index and excludes the last index
14.int size():
This method returns the size of the arraylist.
size() methods start count with 1 not 0.
import java.util.*;
public class Demo
{
public static void main(String[] args)
{
ArrayList<String> l1= new ArrayList<String>();
l1.add("aaa");
l1.add("bbb");
l1.add("ccc");
l1.add("ddd");
l1.add(3,"pppp");
ArrayList<String> l2= new ArrayList<String>();
l2.add("Sangola");
l2.add("college");
l2.addAll(2,l1);
System.out.println("Hello");
System.out.println(l1);
System.out.println("Given element is in the list" l1.contains("college"));
System.out.println("Array list value from l2 beore remove");
for(String s:l2)
{
System.out.println(s);
}
l2.remove(1);
System.out.println("Array list value from l2 after remove");
for(String s:l2)
{
System.out.println(s);
}
System.out.println("Size of Arraylist is "+l2.size());
}
}
import java.util.*;
class demo
{
public static void main(String args[])
{
ArrayList l1= new ArrayList();
l1.add("sangali");
l1.add("kolhapur");
l1.add("satara");
l1.add("pune");
l1.add(11);
l1.add(12.89);
l1.add('a');
System.out.println(l1);
al.remove();
al.remove(3);
al.removeLast();
System.out.println("Linked List Element after remove");
for(Object s:al)
System.out.println(s);
al.clear();
System.out.println("Linked List Element after clear");
for(Object s:al)
System.out.println(s);
}
}
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However,
It is synchronized and contains many methods that are not the part of Collection framework.
1. boolean add(E e)
This method adds element at the end of the vector
2. void add(int index, E element)
This method adds an element at specified index and moves the whole elements one step in
forward direction
3. int capacity()
This method gives the capacity of the vector
4. void clear()
This method clears all the elements in the vector
5. clone clone()
This method gives a duplicate copy of the whole vector
6. boolean contains(Object o)
This method tells whether the vector contains the specified element in the vector, it will
return true if that element is present or false if it is not presen
7.Object firstElement()
This method returns the first element at index 0
8.Object lastElement()
This method returns the last element of the vector
9. Object get(int index)
This method retrieves an element at specified index
import java.util.Vector;
}
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods like
boolean push(), boolean peek(), boolean push(object o), which defines its properties.
Method Modifier Method Description
and
Type
import java.util.Stack;
import java.io.*;
public class Test {
}
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.
Set can be instantiated as:
1. Set<data-type> s1 = new HashSet<data-type>();
2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for
storage. Hashing is used to store the elements in the HashSet. It contains unique items.
Methods of Java HashSet class
Various methods of Java HashSet class are as follows:
SN Modifier & Method Description
Type
}
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends
the HashSet class and implements Set interface. Like HashSet, It also contains unique
elements. It maintains the insertion order and permits null elements. Various methods of
Java LinkedHashSet class are as follows:
SN Modifier & Method Description
Type
import java.util.*;
public class Test {
}
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet,
TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is
quite fast. The elements in TreeSet stored in ascending order.
1. boolean add(Object o):
This methods adds element in the object, which will automatically stores all the elements in
increasing order
2. boolean addAll(Collection c):
This method adds all the elements of one object to another
3. void clear():
This method removes all of the elements from this obje
4. clone clone()
This method gives a duplicate copy of the whole vector
5. boolean contains(Object o)
This method tells whether the vector contains the specified element in the vector, it will
return true if that element is present or false if it is not present
import java.util.*;
public class Test {
t.add(11);
t.add(12);
t.add(13);
t.add(14);
System.out.println("TreeSet Element using foreach loop");
for(Object s:t)
System.out.println(s);
System.out.println("TreeSet Element using iterable");
Iterator<Integer> i= t.iterator();
while(i.hasNext() )
{
System.out.println(i.next());
}
t.remove(3);
System.out.println("TreeSet Element after remove");
for(Object s:t)
System.out.println(s);
System.out.println("11 value is present in treeset " +t.contains(11));
t.clear();
System.out.println("TreeSet Element after clear");
for(Object s:t)
System.out.println(s);
}
Map Interface
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
Java HashMap
Java HashMap class implements the Map interface which allows us to store key and value
pair, where keys should be unique. If you try to insert the duplicate key, it will replace the
element of the corresponding key. It is easy to perform operations using the key index like
updation, deletion, etc. HashMap class is found in the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to
store the null elements as well, but there should be only one null key. Since Java 5, it is
denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the
AbstractMap class and implements the Map interface.
Points to remember
o Java HashMap contains values based on the key.
o Java HashMap contains only unique keys.
o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.
o Java HashMap maintains no order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneabl
e, Serializable
HashMap Methods in JAVA:
1. Object put(Object key, Object value):
This method adds the key value pair to the HashMap object,
2. int size():
This method returns the size of the HashMap
3. void clear():
This method clears all the key value pairs in the HashMap
4. Object clone():
This method returns the exact copy of the HashMap
5. boolean containsKey(Object key):
This method checks the presence of specified key in the HashMap, it will return true if the
key is present and false if the mentioned key is not present
6. boolean containsValue(Object value):
This method checks the presence of specified value in the HashMap, it will return true if the
value is present and false if the mentioned value is not present
7. Set entrySet():
This method returns a Set view of the mappings contained in the HashMap
8.Object get(Object key):
This method returns the value corresponding to the specified key
9.boolean isEmpty():
This method as the name suggests checks whether the HashMap is empty or not, It will
return true if it is empty, or false if it is not empty,
10. Set keySet():
This method returns a Set view of the keys contained in the HashMap
11. putAll(Map m):
This method copies all the key value pair form one hashmap to another
12. Object remove(Object key):
This method as the name specifies removes the key value pair, corresponding to the
mentioned key in the argument list
13. Collection values():
This method returns the collection of all the values in the hashmap
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Map;