Java Collections & JDBC Guide
Java Collections & JDBC Guide
Introduction:
1. An array is an indexed collection of fixed no of homogeneous data elements. (or)
2. An array represents a group of elements of same data type.
3. The main advantage of array is we can represent huge no of elements by using
single variable. So that readability of the code will be improved.
Example:
Student[] s=new Student[10000];
s[0]=new Student();//valid
s[1]=new Customer();//invalid(compile time error)
Compile time error:
Test.java:7: cannot find symbol
Symbol: class Customer
Location: class Test
s[1]=new Customer();
4) Arrays concept is not implemented based on some data structure hence ready-made
methods support we can't expert. For every requirement we have to write the code
explicitly.
Arrays Collections
2) Memory point of view arrays are not 2) Memory point of view collections are highly
recommended to use. recommended to use.
3) Performance point of view arrays are 3) Performance point of view collections are not
recommended to use. recommended to use.
4) Arrays can hold only homogeneous 4) Collections can hold both homogeneous and
data type elements. heterogeneous elements.
Collection:
If we want to represent a group of objects as single entity then we should go for
collections.
Collection framework:
It defines several classes and interfaces to represent a group of objects as a single entity.
Java C++
Collection Containers
Collection framework STL(Standard Template Library)
List:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects as a single entity where
"duplicates are allow and insertion order must be preserved" then we should go
for List interface.
Diagram:
Set:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects as single entity "where
duplicates are not allow and insertion order is not preserved" then we should go
for Set interface.
Diagram:
SortedSet:
1. It is the child interface of Set.
2. If we want to represent a group of individual objects as single entity "where
duplicates are not allow but all objects will be insertion according to some sorting
order then we should go for SortedSet.
(or)
3. If we want to represent a group of "unique objects" according to some sorting
order then we should go for SortedSet.
NavigableSet:
1. It is the child interface of SortedSet.
2. It provides several methods for navigation purposes.
Queue:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects prior to processing then we
should go for queue concept.
Diagram:
Note: All the above interfaces (Collection, List, Set, SortedSet, NavigableSet, and
Queue) meant for representing a group of individual objects.
If we want to represent a group of objects as key-value pairs then we should go for Map.
Map:
1. Map is not child interface of Collection.
2. If we want to represent a group of objects as key-value pairs then we should go for
Map interface.
3. Duplicate keys are not allowed but values can be duplicated.
Diagram:
SortedMap:
1. It is the child interface of Map.
2. If we want to represent a group of objects as key value pairs "according to some
sorting order of keys" then we should go for SortedMap.
NavigableMap:
1) It is the child interface of SortedMap and defines several methods for navigation
purposes.
Collection interface:
• If we want to represent a group of individual objects as a single entity then we
should go for Collection interface. This interface defines the most common general
methods which can be applicable for any Collection object.
• The following is the list of methods present in Collection interface.
1. boolean add(Object o);
2. boolean addAll(Collection c);
3. boolean remove(Object o);
4. boolean removeAll(Object o);
5. boolean retainAll(Collection c);
To remove all objects except those present in c.
6. Void clear();
7. boolean contains(Object o);
8. boolean containsAll(Collection c);
9. boolean isEmpty();
10. Int size();
11. Object[] toArray();
12. Iterator iterator();
ArrayList:
1. The underlying data structure is resizable array (or) growable array.
2. Duplicate objects are allowed.
3. Insertion order preserved.
4. Heterogeneous objects are allowed.(except TreeSet , TreeMap every where
heterogenious objects are allowed)
5. Null insertion is possible.
Constructors:
1) ArrayList a=new ArrayList();
Creates an empty ArrayList object with default initial capacity "10" if ArrayList
reaches its max capacity then a new ArrayList object will be created with
New capacity=(current capacity*3/2)+1
2) ArrayList a=new ArrayList(int initialcapacity);
Creates an empty ArrayList object with the specified initial capacity.
3) ArrayList a=new ArrayList(collection c);
Creates an equivalent ArrayList object for the given Collection that is this constructor
meant for inter conversation between collection objects. That is to dance between
collection objects.
• Usually we can use collection to hold and transfer objects from one tier to another
tier. To provide support for this requirement every Collection class already
implements Serializable and Cloneable interfaces.
• ArrayList and Vector classes implements RandomAccess interface so that any
random element we can access with the same speed. Hence ArrayList is the best
choice of "retrival operation".
• RandomAccess interface present in util package and doesn't contain any methods.
It is a marker interface.
Example
Diagram:
LinkedList:
1. The underlying data structure is double LinkedList
2. If our frequent operation is insertion (or) deletion in the middle then LinkedList is
the best choice.
3. If our frequent operation is retrieval operation then LinkedList is worst choice.
4. Duplicate objects are allowed.
5. Insertion order is preserved.
6. Heterogeneous objects are allowed.
7. Null insertion is possible.
8. Implements Serializable and Cloneable interfaces but not RandomAccess.
Diagram:
Example:
import java.util.*;
class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("ashok");
l.add(30);
l.add(null);
l.add("ashok");
System.out.println(l);//[ashok, 30, null, ashok]
l.set(0,"software");
System.out.println(l);//[software, 30, null,ashok]
l.set(0,"venky");
System.out.println(l);//[venky, 30, null, ashok]
l.removeLast();
System.out.println(l);//[venky, 30, null]
l.addFirst("vvv");
System.out.println(l);//[vvv, venky, 30, null]
}
}
HashSet:
1. The underlying data structure is Hashtable.
2. Insertion order is not preserved and it is based on hash code of the objects.
3. Duplicate objects are not allowed.
4. If we are trying to insert duplicate objects we won't get compile time error and
runtime error add() method simply returns false.
5. Heterogeneous objects are allowed.
6. Null insertion is possible.(only once)
7. Implements Serializable and Cloneable interfaces but not RandomAccess.
8. HashSet is best suitable, if our frequent operation is "Search".
Constructors:
1. HashSet h=new HashSet();
Creates an empty HashSet object with default initial capacity 16 and default fill
ratio 0.75(fill ratio is also known as load factor).
2. HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet object with the specified initial capacity and default fill
ratio 0.75.
3. HashSet h=new HashSet(int initialcapacity,float fillratio);
4. HashSet h=new HashSet(Collection c);
Note : After filling how much ratio new HashSet object will be created , The ratio is called
"FillRatio" or "LoadFactor".
Example:
import java.util.*;
class HashSetDemo
{
public static void main(String[] args)
{
HashSet h=new HashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z"));//false
System.out.println(h);//[null, D, B, C, 10, Z]
}
}
LinkedHashSet:
1. It is the child class of HashSet.
2. LinkedHashSet is exactly same as HashSet except the following differences.
HashSet LinkedHashSet
In the above program if we are replacing HashSet with LinkedHashSet the output is [B, C,
D, Z, null, 10].That is insertion order is preserved.
Example:
import java.util.*;
class LinkedHashSetDemo
{
public static void main(String[] args)
{
LinkedHashSet h=new LinkedHashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z"));//false
System.out.println(h);//[B, C, D, Z, null, 10]
}
}
Note: LinkedHashSet and LinkedHashMap commonly used for implementing "cache
applications" where insertion order must be preserved and duplicates are not allowed.
SortedSet:
1. It is child interface of Set.
2. If we want to represent a group of "unique objects" where duplicates are not
allowed and all objects must be inserting according to some sorting order then we
should go for SortedSet interface.
3. That sorting order can be either default natural sorting (or) customized sorting
order.
SortedSet interface define the following 6 specific methods.
1. Object first();
2. Object last();
3. SortedSet headSet(Object obj);
Returns the SortedSet whose elements are <obj.
4. SortedSet tailSet(Object obj);
It returns the SortedSet whose elements are >=obj.
5. SortedSet subset(Object o1,Object o2);
Returns the SortedSet whose elements are >=o1 but <o2.
6. Comparator comparator();
o Returns the Comparator object that describes underlying sorting technique.
o If we are following default natural sorting order then this method returns
null.
Diagram:
TreeSet:
1. The underlying data structure is balanced tree.
2. Duplicate objects are not allowed.
3. Insertion order is not preserved and it is based on some sorting order of objects.
4. Heterogeneous objects are not allowed if we are trying to insert heterogeneous
objects then we will get ClassCastException.
5. Null insertion is possible(only once).
Constructors:
1. TreeSet t=new TreeSet();
Creates an empty TreeSet object where all elements will be inserted according to
default natural sorting order.
2. TreeSet t=new TreeSet(Comparator c);
Creates an empty TreeSet object where all objects will be inserted according to
customized sorting order specified by Comparator object.
3. TreeSet t=new TreeSet(SortedSet s);
4. TreeSet t=new TreeSet(Collection c);
Example 1:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add("A");
t.add("a");
t.add("B");
t.add("Z");
t.add("L");
//t.add(new Integer(10));//ClassCastException
//t.add(null);//NullPointerException
System.out.println(t);//[A, B, L, Z, a]
}
}
Null acceptance:
• For the empty TreeSet as the 1st element "null" inser on is possible but a er
inser ng that null if we are trying to insert any other we will get
• NullPointerExcep on.
For the non empty TreeSet if we are trying to insert null then we will get
NullPointerExcep on.
Example 2:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("L"));
t.add(new StringBuffer("B"));
System.out.println(t);
}
}
Output:
Runtime Exception.
Note :
• Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer
cannot be cast to java.lang.Comparable
• If we are depending on default natural sorting order compulsory the objects should
be homogeneous and Comparable otherwise we will get ClassCastException.
• An object is said to be Comparable if and only if the corresponding class
implements Comparable interface.
• String class and all wrapper classes implements Comparable interface but
• StringBuffer class doesn't implement Comparable interface hence in the above
program we are getting ClassCastException.
EnumSet in Java
Enumerations or popularly known as enum serve the purpose of representing a group of
named constants in a programming language. For example, the 4 suits in a deck of playing
cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an
enumerated type named Suit.
The EnumSet is one of the specialized implementations of the Set interface for use with
the enumeration type. A few important features of EnumSet are as follows:
• It extends AbstractSet class and implements Set Interface in Java.
• EnumSet class is a member of the Java Collections Framework & is not synchronized.
• It’s a high-performance set implementation, much faster than HashSet.
• All of the elements in an EnumSet must come from a single enumeration type that is
specified when the set is created either explicitly or implicitly.
• It does not allow null Objects and throws NullPointerException if we do so.
• It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the
collection is modified while iterating.
Syntax: Declaration
public abstract class EnumSet<E extends Enum<E>>
Here, E specifies the elements. E must extend Enum, which enforces the requirement that the
elements must be of the specified enum type.
Methods of EnumSet
Method Action Performed
Creates an enum set with the same element type as the specified
complementOf
enum set, initially containing all the elements of this type that are
(EnumSet<E> s)
not contained in the specified set.
copyOf
Creates an enum set initialized from the specified collection.
(Collection<E> c)
copyOf Creates an enum set with the same element type as the specified
(EnumSet<E> s) enum set, initially containing the same elements (if any).
noneOf(Class<E>
Creates an empty enum set with the specified element type.
elementType)
Method Action Performed
of(E e1, E e2) Creates an enum set initially containing the specified elements.
of(E first, E… rest) Creates an enum set initially containing the specified elements.
of(E e1, E e2, E e3) Creates an enum set initially containing the specified elements.
// Enum
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };
// Main class
// EnumSetExample
public class GFG {
// Creating a set
EnumSet<Gfg> set1, set2, set3, set4;
// Adding elements
set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
Gfg.LEARN, Gfg.CODE);
set2 = EnumSet.complementOf(set1);
set3 = EnumSet.allOf(Gfg.class);
set4 = EnumSet.range(Gfg.CODE, Gfg.CONTRIBUTE);
// Printing corresponding elements in Sets
System.out.println("Set 1: " + set1);
System.out.println("Set 2: " + set2);
System.out.println("Set 3: " + set3);
System.out.println("Set 4: " + set4);
}
}
Output
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Set 2: [MCQ]
Set 3: [CODE, LEARN, CONTRIBUTE, QUIZ, MCQ]
Set 4: [CODE, LEARN, CONTRIBUTE]
3 cursors of java:
If we want to get objects one by one from the collection then we should go for cursor.
There are 3 types of cursors available in java. They are:
1. Enumeration
2. Iterator
3. ListIterator
Enumeration:
1. We can use Enumeration to get objects one by one from the legacy collection
objects.
2. We can create Enumeration object by using elements() method.
public Enumeration elements();
Enumeration e=v.elements();
using Vector Object
Example:
import java.util.*;
class EnumerationDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=0;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v);//[0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
if(i%2==0)
System.out.println(i);//0 2 4 6 8 10
}
System.out.print(v);//[0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10]
}
}
Limitations of Enumeration:
1. We can apply Enumeration concept only for legacy classes and it is not a universal
cursor.
2. By using Enumeration we can get only read access and we can't perform remove
operations.
3. To overcome these limitations sun people introduced Iterator concept
in 1.2v.
Iterator:
1. We can use Iterator to get objects one by one from any collection object.
2. We can apply Iterator concept for any collection object and it is a universal cursor.
3. While iterating the objects by Iterator we can perform both read and remove
operations.
Example:
import java.util.*;
class IteratorDemo
{
public static void main(String[] args)
{
ArrayList a=new ArrayList();
for(int i=0;i<=10;i++)
{
a.add(i);
}
System.out.println(a);//[0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10]
Iterator itr=a.iterator();
while(itr.hasNext())
{
Integer i=(Integer)itr.next();
if(i%2==0)
System.out.println(i);//0, 2, 4, 6,
8, 10
else
itr.remove();
}
System.out.println(a);//[0, 2, 4, 6, 8, 10]
}
}
Limitations of Iterator:
1. Both enumeration and Iterator are single direction cursors only. That is we can
always move only forward direction and we can't move to the backward direction.
2. While iterating by Iterator we can perform only read and remove operations and
we can't perform replacement and addition of new objects.
3. To overcome these limitations sun people introduced listIterator concept.
ListIterator:
if(s.equals("chiru"))
{
itr.set("chran");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chran, nag]
Case 2:
if(s.equals("nag"))
{
itr.add("chitu");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chiru, nag, chitu]
The most powerful cursor is listIterator but its limitation is it is applicable only for "List
objects".
Iterator vs Foreach in Java
Background :
Iterator is an interface provided by collection framework to traverse a collection and for a
sequential access of items in the collection.
While using nested for loops it is better to use for-each loop, consider the below code for
better understanding.
import java.util.*;
Output:
In the above code we are calling the next() method again and again for itr1 (i.e., for List l).
Now we are advancing the iterator without even checking if it has any more elements left in
the collection(in the inner loop), thus we are advancing the iterator more than the number of
elements in the collection which leads to NoSuchElementException.
for-each loops are tailor made for nested loops. Replace the iterator code with the below
code.
// Java program to demonstrate working of nested for-each
import java.util.*;
public class Main
{
public static void main(String args[])
{
// Create a link list which stores integer elements
List<Integer> l=new LinkedList<Integer>();
Output:
22233344
for(Customer c : arr)
System.out.println(c);
}
}
getOrDefault(Object key, Returns the value to which the specified key is mapped, or
V defaultValue) defaultValue if this map contains no mapping for the key
import java.util.*;
// Main class
class GFG {
// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}
Output:
a:100
b:200
c:300
d:400