0% found this document useful (0 votes)
6 views23 pages

Collections in Java

Java
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views23 pages

Collections in Java

Java
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

COLLECTIONS IN JAVA

LOGESWARAN K
COLLECTIONS
 COLLECTIONS
 Collection represents a group of individual object as single unit or
entity .
 Sometimes called a container.
 All the operations that you perform on a data such as searching,
sorting, insertion, manipulation, deletion etc. can be performed by
Java Collections
 The java.util package contains all the classes and interfaces for
Collection framework
 COLLECTION FRAMEWORK
 It defines several classes and interfaces which can be used to
represent and manipulated the group of object as a single entity.
 It includes: Interfaces, Classes and Algorithms
HIERARCHY
METHODS OF COLLECTION INTERFACE
No. Method Description

1 public boolean add(Object element) is used to insert an element in this collection.


2 public boolean addAll(Collection c) is used to insert the specified collection elements in the
invoking collection.
3 public boolean remove(Object is used to delete an element from this collection.
element)
4 public boolean removeAll(Collection c) is used to delete all the elements of specified collection
from the invoking collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of invoking collection
except the specified collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
8 public boolean contains(Object is used to search an element.
element)
9 public boolean containsAll(Collection is used to search the specified collection in this
c) collection.
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object element) matches two collection.
14 public int hashCode() returns the hashcode number for collection.
ITERATOR INTERFACE
 Iterator interface provides the facility of iterating the
elements in forward direction only
 Methods of Iterator interface

No. Method Description

1 public boolean hasNext() It returns true if iterator has more


elements.
2 public Object next() It returns the element and moves the
cursor pointer to the next element.

3 public void remove() It removes the last elements returned by


the iterator. It is rarely used.
JAVA ARRAYLIST CLASS
 Java ArrayList class uses a dynamic array for storing
the elements
 It inherits Abstract List class and implements List
interface.
 Points:

 Java ArrayList class


 contain duplicate elements.

 maintains insertion order.

 allows random access because array works at the


index basis.
 manipulation is slow because a lot of shifting
needs to be occurred if any element is removed
from the array list.
CONSTRUCTORS OF ARRAYLIST

Constructor Description

ArrayList() It is used to build an empty array list.

It is used to build an array list that is initialized


ArrayList(Collection c)
with the elements of the collection c.

It is used to build an array list that has the specified


ArrayList(int capacity)
initial capacity.
METHODS OF ARRAYLIST
Method Description
It is used to insert the specified element at the specified position
void add(int index, Object element)
index in a list.
It is used to append all of the elements in the specified collection
boolean addAll(Collection c) to the end of this list, in the order that they are returned by the
specified collection's iterator.
void clear() It is used to remove all of the elements from this list.
It is used to return the index in this list of the last occurrence of
int lastIndexOf(Object o) the specified element, or -1 if the list does not contain this
element.
It is used to return an array containing all of the elements in this
Object[] toArray()
list in the correct order.
It is used to return an array containing all of the elements in this
Object[] toArray(Object[] a)
list in the correct order.
boolean add(Object o) It is used to append the specified element to the end of a list.
It is used to insert all of the elements in the specified collection
boolean addAll(int index, Collection c)
into this list, starting at the specified position.
Object clone() It is used to return a shallow copy of an ArrayList.
It is used to return the index in this list of the first occurrence of
int indexOf(Object o) the specified element, or -1 if the List does not contain this
element.
It is used to trim the capacity of this ArrayList instance to be the
void trimToSize()
list's current size.
EXAMPLE
import java.util.*;
class Collection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay"); OUTPUT:
//Traversing list through Iterator Ravi
Vijay
Iterator itr=list.iterator(); Ravi
while(itr.hasNext()){ Ajay
System.out.println(itr.next());
}
}
}
ANOTHER EXAMPLE
import java.util.*;
class Collection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay"); OUTPUT:
al.add("Ravi"); Ravi
Vijay
al.add("Ajay"); Ravi
Ajay
for(String obj:al)
System.out.println(obj);
}
}
EXAMPLE OF ADDALL(COLLECTION C) METHOD
import java.util.*;
class Collection3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
list.addAll(al2);//adding second list in first list
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} }}
EXAMPLE OF REMOVEALL() METHOD
import java.util.*;
public class Collections4 {
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi"); OUTPUT:
al.add("Vijay"); iterating the elemen
ts after removing th
al.add("Ajay"); e elements of al2...
ArrayList<String> al2=new ArrayList<String>();
Vijay
al2.add("Ravi");
Ajay
al2.add("Hanumat");
al.removeAll(al2);
System.out.println("iterating the elements after removing the elements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} }}
EXAMPLE OF RETAINALL() METHOD
import java.util.*;
public class Collections5 { OUTPUT:
iterating the element
public static void main(String args[]){
s after retaining the
ArrayList<String> al=new ArrayList<String>(); elements of al2...
al.add("Ravi");
al.add("Vijay"); Ravi
Ajay
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al2.add("Ajay");
al.retainAll(al2);
System.out.println("iterating the elements after retaining the elements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} }}
ARRAYLIST
class MyArrayList
{
public static void main(String a[])
{
ArrayList<Integer> al=new
ArrayList<Integer>();
al.add(4); Before sorting:[4, 2, 3, 1, 6, 5]
al.add(2); [1, 2, 3, 4, 5, 6]
al.add(3); [1, 2, 3, 4, 5, 6]
al.add(1);
al.add(6);
al.add(5);
System.out.println("Before sorting:"+al);
Collections.sort(al);
ArrayList<Integer> af=new
ArrayList<Integer>(al);
//af.addAll(al);

System.out.println(al);
System.out.println(af);
ArrayList ag=new ArrayList(10);
ag.add("Alpha");
ag.addAll(af);
boolean x=ag.contains("Alpha"); CONTD…
if(x)
System.out.println("Alpha is present in the Alpha is present in the list....
list....");
System.out.println(ag); [Alpha, 1, 2, 3, 4, 5, 6]
ag.add(6,"iit");
ag.add(8,"IT"); [Alpha, 1, 2, 3, 4, 5, iit, 6, IT, MIT,
ag.add("MIT"); Google, google, isro]
ag.add(10,"Google");
ag.add("google"); [Alpha, 1, 2, 3, 4, 5, iit, 6, IT, MIT,
ag.add(12,"isro"); Google, isro, 1]
System.out.println(ag);
ag.remove(11); //remove the element at the Size:13
index
ag.add(1); //duplicate allowed get(10):Google
System.out.println(ag);
System.out.println("Size:"+ag.size()); set(10):Google
System.out.println("get(10):"+ag.get(10));
System.out.println("set(10):"+ag.set(10,"face [Alpha, 1, 2, 3, 4, 5, iit, 6, IT, MIT,
book")); // set the value at the index and facebook, isro, 1]
return the old value
System.out.println(ag); indexOf():7
sum of integer array:21
List:[kongu, IT, II, B]
After str.removeAll(sub):[IT, II]
System.out.println("indexOf():"+ag.indexOf( CONTD…
6)); // return the index of 1st occurence of
the element
indexOf():7
Integer s[]=new Integer[al.size()]; //
create an array with size specified sum of integer array:21
s=al.toArray(s); // array list converted to
array List:[kongu, IT, II, B]
int sum=0;
for(int i=0;i<s.length;i++) After str.removeAll(sub):[IT, II]
{
sum=sum+s[i];
}
System.out.println("sum of integer
array:"+sum);
ArrayList<String>str=new
ArrayList<String>();
str.add("kongu");
str.add("IT");
str.add("II");
str.add("B");
CONTD…
System.out.println("List:"+str);
List sub=str.subList(1,3); // includes 2 but
List:[kongu, IT, II, B]
not 3
After str.removeAll(sub):[IT, II]
//System.out.println("Sub list:"+sub);
//str.removeAll(sub);

str.retainAll(sub);
System.out.println("After
str.removeAll(sub):"+str);

}
}
HASHSET CLASS
 HashSet class is used to create a collection that uses a hash
table for storage
 It inherits the Abstract Set class and implements Set
interface
 List can contain duplicate elements whereas Set contains
unique elements only.
 Points:
 HashSet is an unordered collection
 HashSet uses a mechanism called "Hashing" to store the
elements.
 It uses a hashtable data structure to store the elements.
 It contains unique elements.
 It allows storing the null values.
 It does not provide a mechanism to maintain the insertion order.
So the elements will be inserted based on the Hashcode.
 It is a useful mechanism for the search operation.
 By default, it uses 16 as the initial size of the hashtable.
 It extends AbstractSet class and implements the Set interface.
 It also implements the Cloneable and Serializable interface.
import java.util.*;
class hashset
{
public static void main(String r[])
{
HashSet<String> hs=new HashSet<String>();
hs.add("A");
hs.add("B");
hs.add("C");
hs.add(“A"); // duplicates not added.
Iterator<String> i=hs.iterator(); // use iterator to get objects
while(i.hasNext())
{
System.out.println(i.next());
}
System.out.println(hs);
System.out.println("hashcode:"+hs.hashCode());
}
}
CONSTRUCTORS OF HASHSET CLASS
Constructor Description
It is used to construct a default
HashSet()
HashSet.
HashSet(Collecti It is used to initialize the hash set by
on c) using the elements of the collection c.
It is used to initialize the capacity of the
HashSet(int
hash set to the given integer value
capacity)
capacity. The capacity grows
default
automatically as elements are added to
capacity:16
the HashSet.
HashSet(int
default fill ratio:0.75 (0.1 to 1.0)
capacity, float
fillRatio)
METHODS OF HASHSET CLASS
Method Description
void clear() It is used to remove all of the elements from this set.
boolean contains(Object It is used to return true if this set contains the specified
o) element.
It is used to adds the specified element to this set if it is
boolean add(Object o)
not already present.

boolean isEmpty() It is used to return true if this set contains no elements.

It is used to remove the specified element from this set


boolean remove(Object o)
if it is present.
It is used to return a shallow copy of this HashSet
Object clone()
instance: the elements themselves are not cloned.
It is used to return an iterator over the elements in this
Iterator iterator()
set.
int size() It is used to return the number of elements in this set.
PRIORITYQUEUE CLASS
 The interface Queue is available in the java.util package
 Interface Queue is used to keep the elements that are
processed in the First In First Out (FIFO) manner.
 It is an ordered list of objects, where insertion of elements
occurs at the end of the list, and removal of elements
occur at the beginning of the list.
 Most common classes for implementing queue interface
are the LinkedList and PriorityQueue
 PriorityQueue gives us a way for processing the objects
on the basis of priority
 In PriorityQueue elements of the queue can be
processed according to the priority
 Refer example program

You might also like