Collection Framework
Collection Framework
Collection Framework
Consider below example of association:
class Date{ }
class Addresss{ }
class Person{
private String name = new String();
private Date birthDate = new Date();
private Address currentAddress = new Address();
}
class Program{
public static void main(String[] args) {
Person p = new Person( );
}
}
In Java, instance do not get space inside another instance. Rather instance contains reference of another instance.
Library
In Java, .jar file is a library file which can contain manifest file, resources, packages.
Package can contain sub package, interface, class, enum, exception, error, annotation types
Framework
Framework = collection of libraries + tools + rules/guidelines
It is reusable partial code on the top of it we can develop application.
Examples:
JUnit: Unit testing framework which is used to write test case.
Apache Log4j2: Logging framework which is used to record activities.
AWT/Swing/Java-FX: GUI framework.
JNI: Framework to access native code
Struts: Readymade MVC based web application framework.
Hibernate: ORM based automatic persistence framework
Spring: Enterprise framework
Collection Framework
Any instance which contains multiple elements is called as collection. In java, data structure class is also called as collection.
Collection framework is a library of data structure classes on the top of it we can develop Java application.
In Java, collection framework is all about how to use readymade data structure class not about how to implement user defined data structure class.
In Java, when we use collection to store instance then it doesnt contain instance rather it contains reference of the instance.
To use collection framework, we should import java.util package.
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
Iterable
It is interface declared in java.lang package.
It is introduced in jDK 1.5.
Implementing this interface allows an object to be the target of the "for-each loop" statement.
Methods:
Iterator iterator()
default Spliterator spliterator()
default void forEach(Consumer<? super T> action)
Collection
Value stored inside any collection( Array, Stack, Queue, LinkedList etc.) is called as element.
Collection is interface declared in java.util package. It is root interface in the collection framework interface hierarchy.
The JDK does not provide any direct implementations of Collection interface.
Direct implementation classes of Collection interface are:
AbstractList
AbstractQueue
AbstractSet
List, Queue, Set are sub interfaces of java.util.Collection interface.
Below are the methods of java.util.Collection interface.
Abstract methods:
boolean add(E e)
boolean addAll(Collection<? extends E> c)
void clear()
boolean contains(Object o)
boolean containsAll(Collection<?> c)
boolean isEmpty()
boolean remove(Object o)
boolean removeAll(Collection<?> c)
boolean retainAll(Collection<?> c)
int size()
Object[] toArray()
T[] toArray(T[] a)
Default methods:
default Stream stream()
default Stream parallelStream()
default boolean removeIf(Predicate<? super E> filter)
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
List
This interface is a member of the Java Collections Framework and introduced in JDK 1.2
List is sub interface of Collection interface. It means that all the methods of Collection interafce will be inherited into List interface.
Direct implementation classes of List interfaces are:
AbstractList
ArrayList
Vector
Stack
LinkedList
These collection classes are called as List collections.
Inside List collection we can store data in sequential fashion.
We can store duplicate elements inside any List collection.
We can store multiple null values inside List collection.
With the help of integer index, we can access elements from List collection.
We can traverse elements of any List collection using Iterator as well as ListIterator.
Below are the methods declared in java.util.List interface.
Abstract methods:
void add(int index, E element)
boolean addAll(int index, Collection<? extends E> c)
E remove(int index)
E get(int index)
E set(int index, E element)
int indexOf(Object o)
int lastIndexOf(Object o)
ListIterator listIterator()
ListIterator listIterator(int index)
List subList(int fromIndex, int toIndex)
Default methods of:
default void sort(Comparator<? super E> c)
default void replaceAll(UnaryOperator operator)
Note: If we want to manage elements of non final type inside any List collection then we should override at least equals methods inside non final type.
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
ArrayList
Method Summary:
public void ensureCapacity(int minCapacity)
protected void removeRange(int fromIndex, int toIndex)
public void trimToSize()
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
Instantiation:
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
List<Integer> list = Program.getList();
Integer element = list.get( list.size() ); //IndexOutOfBoundsException
}
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
list.add(50);
return list;
}
public static void main(String[] args) {
List<Integer> list = Program.getList();
ListIterator<Integer> itr = list.listIterator();
Integer element = null;
while( itr.hasNext()) {
element = itr.next();
System.out.print( element+" ");
}
System.out.println();
while( itr.hasPrevious()) {
element = itr.previous();
System.out.print( element+" ");
}
}
//Object[] elementData;
private static int capacity(List<Integer> list) throws Exception{
Class<?> c = list.getClass();
Field field = c.getDeclaredField("elementData");
field.setAccessible(true);
Object[] elementData = (Object[]) field.get(list);
return elementData.length;
}
public static void main(String[] args) {
try {
List<Integer> list = Program.getList();
System.out.println("Size : "+list.size()); //5
How will you search and remove single element from ArrayList?
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
System.out.println(list); //[50, 10, 30, 20, 40]
//Collections.sort( list );
list.sort(null);
System.out.println(list); //[10, 20, 30, 40, 50]
}
Vector
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
During traversing, without iterator, if we try to make changes in underlying collection and if we do not get ConcurrentModificationException then such
iterator is called as fail-safe Iterator. Such iterators works by creating copy of the Collection.
LinkedList
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
}
}
Deque
It is sub interface of Queue interface.
The name deque is short for "double ended queue" and is usually pronounced "deck".
This interface is a member of the Java Collections Framework.
It is introduced in JDK 1.6
Set
set.add(50);
set.add(10);
set.add(30);
set.add(20);
set.add(40);
System.out.println( set );
}
Algorithm
In Computer science algorithm and data structure are two different branches.
Data structure describes 2 things:
How to organize data inside RAM?
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
Hashing is a technique used to store and retrieve data in a fast and efficient manner.
Hashing searching is based on hash code.
Hashcode is not an index / address / reference. It is a logical integer number that can be generated by processing state of the instance.
To generate hash code we should use hash function. Consider following example
In the context of hashing, a slot refers to a location in the hash table where a key-value pair can be stored.
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
In other words, hash code is required to generate index which is called as slot in hashing.
By Processing state of the instance, if we get same slot then it is called as collision.
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
Separate Chaining
To avoid collision, we can maintain one collection(LinkedList/BST) per slot. It is called as bucket.
Note: If we want to store any element of non primitive type inside Hashcode based collection then we should override equals and hashCode method
inside non primitive type.
Pros of Hashing
Fast retrieval: Hashing allows for constant-time retrieval of data, regardless of the size of the data set. This makes it a very efficient searching
algorithm.
Flexibility: Hashing can be used to search for any type of data, including strings, numbers, and custom objects.
Easy to implement
Supports dynamic resizing: Hash tables can be resized dynamically to accommodate more data, without having to recreate the entire data
structure.
Cons of Hashing:
Hash collisions: Hash collisions occur when two different keys are mapped to the same hash value. This can result in slower lookup times and may
require additional processing to resolve the collision.
Memory usage: Hash tables can consume a lot of memory, particularly if the data set is large. This can lead to performance issues if the available
memory is limited.
Hash functions: The efficiency of hashing depends on the quality of the hash function used. Poor hash functions can lead to more collisions, slower
retrieval times, and other issues.
equals and hashCode are non final methods of java.lang.Object class.
If we do not override equals method then super class's equals method will call. equals method of Object class do not compare state of instances. It
compares state of references.
Consider equals method definition of Object class:
hashCode() method of java.lang.Object class convert memory address of instance into integer value. Hence even though state of the instances are same
we get different hashCode. If we want hashCode based on state of the instance then we should override hashCode method inside class.
Consider implementation:
@Override
public int hashCode() {
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
int prime = 31;
int result = 1;
result = result * prime + this.empid;
return result;
}
HashSet
It is hashCode based collection whose implementation is based on Hashtable.
In HashSet elements get space according its hash code hence It doesn't give any gurantee about order of the elements.
Since it is Set collection, it doesn't contain duplicate elements.
HashSet can contain null element.
It is unsynchronized collection. Using Collections.synchronizedSet() method we can consider it synchronized.
This class is a member of the Java Collections Framework.
It is introduced in JDK 1.2
If we want to use any element of non final type inside HashSet then non final type should override equals() and hashCode() method.
Instantiation of HashSet:
set.add(101);
set.add(125);
set.add(13);
set.add(314);
set.add(215);
set.add(null);
System.out.println(set); //[null, 101, 215, 314, 125, 13]
}
LinkedHashSet
It is hashCode based collection whose implementation is based on Hashtable and LinkedList.
During traversing it maintains order of lements.
Since it is Set collection, it doesn't contain duplicate elements.
HashSet can contain null element.
It is unsynchronized collection. Using Collections.synchronizedSet() method we can consider it synchronized.
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
public class Program {
public static Dictionary<Integer, String> getDictionary( ){
Dictionary<Integer, String> d = new Hashtable<>(); //Upcasting
d.put(1,"PreDAC");
d.put(2,"DAC");
d.put(3,"DMC");
d.put(4,"DIVESD");
d.put(5,"DESD");
d.put(6,"DBDA");
return d;
}
private static void countAndPrintEntries(Dictionary<Integer, String> d) {
System.out.println("Count of entries : "+d.size());
}
private static void printKeys(Dictionary<Integer, String> d) {
Enumeration<Integer> keys = d.keys();
Integer key = null;
while( keys.hasMoreElements()) {
key = keys.nextElement();
System.out.println( key );
}
}
private static void printValues(Dictionary<Integer, String> d) {
Enumeration<String> values = d.elements();
String value = null;
while( values.hasMoreElements()) {
value = values.nextElement();
System.out.println(value);
}
}
private static void printValue(Dictionary<Integer, String> d, int courseId) {
Integer key = new Integer( courseId );
String value = d.get(key);
if( value != null )
System.out.println(key+" "+value);
else
System.out.println("Invalid key");
}
private static void removeEntry(Dictionary<Integer, String> d, int courseId) {
Integer key = new Integer( courseId );
String value = d.remove(key);
if( value != null )
System.out.println(key+" "+value+" is removed");
else
System.out.println("Invalid key");
}
public static void main(String[] args) {
Dictionary<Integer, String> d = Program.getDictionary();
//Program.countAndPrintEntries( d );
//Program.printKeys( d );
//Program.printValues( d );
//Program.printValue( d, 2 );
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
Program.removeEntry( d, 200);
}
}
This class is obsolete. New implementations should implement the Map interface, rather than extending this class.
Map<K,V>
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
Consider example:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + number;
return result;
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (number != other.number)
return false;
return true;
}
@Override
public String toString() {
return String.format("%-10d%-15s%8.2f", this.number, this.type, this.balance);
}
}
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.example.domain.Account;
import org.example.domain.Customer;
import java.util.Hashtable;
import java.util.Scanner;
import org.example.domain.Account;
import org.example.domain.Customer;
import org.example.test.MapTest;
HashMap<K,V>
It is a sub class of AbstractMap<K,V> class and it implements Map<K,V>
Its implementation is based on Hash table.
Since it is Map collection, we can not insert duplicate keys but we can insert duplcate value.
In HashMap<K,V> key and value can be null.
It is unsynchronized collection. Using Collections.synchronizedMap() method we can consider it synchronized.
This class is a member of the Java Collections Framework.
It is introduced in JDK 1.2.
If we want to use any element of non final type inside Hashtable then non final type should override equals and hashCode method.
Instantiation:
LinkedHashMap<K,V>
It is a sub class of HashMap<K,V>.
Its implementation is based on Hash table and linked list.
During traversing it maintains order of elements.
Since it is Map collection, we can not insert duplicate keys but we can insert duplcate value.
In HashMap<K,V> key and value can be null.
It is unsynchronized collection. Using Collections.synchronizedMap() method we can consider it synchronized.
This class is a member of the Java Collections Framework.
It is introduced in JDK 1.2.
If we want to use any element of non final type inside Hashtable then non final type should override equals and hashCode method.
Instantiation:
sandeepkulange@gmail.com | 9527325202
Object Oriented Programming with Java
TreeMap<K,V>
It is a sub class of AbstractMap<K,V> class and it implements NavigableMap<K,V>
Its implementation is based on Red Black Tree.
TreeMap store entries in sorted order.
Since it is Map collection, we can not insert duplicate keys but we can insert duplcate value.
In TreeMap<K,V> key can not be null but value can be null.
It is unsynchronized collection. Using Collections.Collections.synchronizedSortedMap() method we can consider it synchronized.
This class is a member of the Java Collections Framework.
It is introduced in JDK 1.2.
If we want to use any element of non final type inside TreeMap then non final type should implement Comparable interface.
Instantiation:
sandeepkulange@gmail.com | 9527325202