0% found this document useful (0 votes)
21 views25 pages

Java Collections & JDBC Guide

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

Java Collections & JDBC Guide

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

UNIT V COLLECTIONS FRAMEWORK & DATABASE CONNECTIVITY

Collections Framework-Autoboxing -For-Each Style for Loop-Collection Interfaces-


Collection Interface-List Interface-Set Interface -Sorted Set Interface-Collection Classes-
Array List Class-LinkedList Class-HashSet Class-LinkedHashSet Class-Tree Set Class-
Enum Set Class-Accessing a Collection via an Iterator-Using an Iterator-The For-Each
Alternative to Iterators-Storing User-Defined Classes in Collections-Working with Maps-The
Map Interfaces-The Map Classes-Arrays- Accessing databases using JDBC connectivity -
DAO

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.

Limitations of Object[] array:


1. Arrays are fixed in size that is once we created an array there is no chance of
increasing (or) decreasing the size based on our requirement hence to use arrays
concept compulsory we should know the size in advance which may not possible
always.
2. Arrays can hold only homogeneous data elements.

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();

3) But we can resolve this problem by using object type array(Object[]).


Example:
Object[] o=new Object[10000];
o[0]=new Student();
o[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.

To overcome the above limitations we should go for collections concept.

1. Collections are growable in nature that is based on our requirement we can


increase (or) decrease the size hence memory point of view collections concept is
recommended to use.
2. Collections can hold both homogeneous and heterogeneous objects.
3. Every collection class is implemented based on some standard data structure
hence for every requirement ready-made method support is available being a
programmer we can use these methods directly without writing the functionality
on our own.

Differences between Arrays and Collections

Arrays Collections

1) Arrays are fixed in size. 1) Collections are growable in nature.

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.

5) There is no underlying data structure 5) Every collection class is implemented based on


for arrays and hence there is no some standard data structure and hence
readymade method support. readymade method support is available.
6) Arrays can hold both primitives and 6) Collections can hold only objects but not
object types. primitives.

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)

9(Nine) key interfaces of collection framework:


1. Collection
2. List
3. Set
4. SortedSet
5. NavigableSet
6. Queue
7. Map
8. SortedMap
9. NavigableMap
Collection:
1. If we want to represent a group of "individual objects" as a single entity then we
should go for collection.
2. In general we can consider collection as root interface of entire collection
framework.
3. Collection interface defines the most common methods which can be applicable
for any collection object.
4. There is no concrete class which implements Collection interface directly.

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.

What is the difference between Collection and Collections ?


"Collection is an "interface" which can be used to represent a group of objects as a
single entity. Whereas "Collections is an utility class" present in java.util package to
define several utility methods for Collection objects.
Collection--------------------interface
Collections------------------class

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();

There is no concrete class which implements Collection interface directly.


List interface:
• It is the child interface of Collection.
• If we want to represent a group of individual objects as a single entity where
duplicates are allow and insertion order is preserved. Then we should go for List.
• We can differentiate duplicate objects and we can maintain insertion order by
means of index hence "index play very important role in List"

List interface defines the following specific methods.


1. boolean add(int index,Object o);
2. boolean addAll(int index,Collectio c);
3. Object get(int index);
4. Object remove(int index);
5. Object set(int index,Object new);//to replace
6. Int indexOf(Object o);
Returns index of first occurrence of "o".
7. Int lastIndexOf(Object o);
8. ListIterator listIterator();

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.

Demo program for ArrayList:


import java.util.*;
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList a=new ArrayList();
a.add("A");
a.add(10);
a.add("A");
a.add(null);
System.out.println(a);//[A, 10, A, null]
a.remove(2);
System.out.println(a);//[A, 10, null]
a.add(2,"m");
a.add("n");
System.out.println(a);//[A, 10, m, null, n]
}
}

• 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.

Getting synchronized version of ArrayList object:


Collections class defines the following method to return synchronized version of
List.
Public static List synchronizedList(list l);

Example

• ArrayList is the best choice if our frequent operation is retrieval.


• ArrayList is the worst choice if our frequent operation is insertion (or) deletion in the
middle because it requires several internal shift operations.

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:

Usually we can use LinkedList to implement Stacks and Queues.


To provide support for this requirement LinkedList class defines the following 6 specific
methods.
1. void addFirst(Object o);
2. void addLast(Object o);
3. Object getFirst();
4. Object getLast();
5. Object removeFirst();
6. Object removeLast();
We can apply these methods only on LinkedList object.
Constructors:
1. LinkedList l=new LinkedList();
Creates an empty LinkedList object.
2. LinkedList l=new LinkedList(Collection c);
To create an equivalent LinkedList object for the given collection.

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

1) The underlying data structure 1) The underlying data structure is a combination of


is Hashtable. LinkedList and Hashtable.

2) Insertion order is not


2) Insertion order is preserved.
preserved.

3) Introduced in 1.2 v. 3) Introduced in 1.4v.

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.

The Hierarchy of EnumSet is as follows:


java.lang.Object
↳ java.util.AbstractCollection<E>
↳ java.util.AbstractSet<E>
↳ java.util.EnumSet<E>
Here, E is the type of elements stored.

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

allOf(Class<E> Creates an enum set containing all of the elements in the


elementType) specified element type.

clone() Returns a copy of this set.

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 e) Creates an enum set initially containing the specified element.

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.

of(E e1, E e2, E e3,


Creates an enum set initially containing the specified elements.
E e4)

of(E e1, E e2, E e3,


Creates an enum set initially containing the specified elements.
E e4, E e5)

Creates an enum set initially containing all of the elements in the


range(E from, E to)
range defined by the two specified endpoints.

// Java Program to Illustrate Working


// of EnumSet and its functions

// Importing required classes


import java.util.EnumSet;

// Enum
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };

// Main class
// EnumSetExample
public class GFG {

// Main driver method


public static void main(String[] args) {

// 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

Enumeration interface defines the following two methods

1. public boolean hasMoreElements();


2. public Object nextElement();

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.

We can get Iterator object by using iterator() method of Collection interface.


public Iterator iterator();
Iterator itr=c.iterator();

Iterator interface defines the following 3 methods.

1. public boolean hasNext();


2. public object next();
3. public void remove();

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:

1. ListIterator is the child interface of Iterator.


2. By using listIterator we can move either to the forward direction (or) to the
backward direction that is it is a bi-directional cursor.
3. While iterating by listIterator we can perform replacement and addition of new
objects in addition to read and remove operations

By using listIterator method we can create listIterator object.

public ListIterator listIterator();


ListIterator itr=l.listIterator();
(l is any List object)

ListIterator interface defines the following 9 methods.

1. public boolean hasNext();


2. public Object next(); forward
3. public int nextIndex();
4. public boolean hasPrevious();
5. public Object previous(); backward
6. public int previousIndex();
7. public void remove();
8. public void set(Object new);
9. public void add(Object new);
Example:
import java.util.*;
class ListIteratorDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("balakrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
System.out.println(l);//[balakrishna, venki,
chiru, nag]
ListIterator itr=l.listIterator();
while(itr.hasNext())
{
String s=(String)itr.next();
if(s.equals("venki"))
{
itr.remove();
}
}
System.out.println(l);//[balakrishna, chiru, nag]
}
}
Case 1:

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.

// Iterating over collection 'c' using iterator


for (Iterator i = c.iterator(); i.hasNext(); )
System.out.println(i.next());
For eachloop is meant for traversing items in a collection.

// Iterating over collection 'c' using for-each


for (Element e: c)
System.out.println(e);
We read the ‘:’ used in for-each loop as “in”. So loop reads as “for each element e in
elements”, here elements is the collection which stores Element type items.
elements.forEach (e  System.out.println(e) );

When to use which traversal?

If we have to modify collection, we can use Iterator.

While using nested for loops it is better to use for-each loop, consider the below code for
better understanding.

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>();

// Now add elements to the Link List


l.add(2);
l.add(3);
l.add(4);

// Make another Link List which stores integer elements


List<Integer> s=new LinkedList<Integer>();
s.add(7);
s.add(8);
s.add(9);

// Iterator to iterate over a Link List


for (Iterator<Integer> itr1=l.iterator(); itr1.hasNext(); )
{
for (Iterator<Integer> itr2=s.iterator(); itr2.hasNext(); )
{
if (itr1.next() < itr2.next())
{
System.out.println(itr1.next());
}
}
}
}
}

Output:

Exception in thread "main" java.util.NoSuchElementException


at java.util.LinkedList$ListItr.next(LinkedList.java:888)
at Main.main(Main.java:29)
The above code throws java.util.NoSuchElementException.

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>();

// Now add elements to the Link List


l.add(2);
l.add(3);
l.add(4);

// Make another Link List which stores integer elements


List<Integer> s=new LinkedList<Integer>();
s.add(2);
s.add(4);
s.add(5);
s.add(6);

// Iterator to iterate over a Link List


for (int a:l)
{
for (int b:s)
{
if (a<b)
System.out.print(a + " ");
}
}
}
}

Output:

22233344

User-Defined Objects in Collections


Collection classes are used to store built in objects such as Integer, String, Character
etc. But the potential of collection classes isn't just restricted to the storage of built-in objects.
Collections classes can store any similar type of objects, be it objects of a built-in class or
objects of an user-defined class. This feature of collection class is very userful when we are
making an application which requires us to store many objects of user-defined classes and not
just objects of built-in classes.
In this example, we have created a Customer class with three instance variables - name,
balance and ID, together they make up an object of Customer class. We are going to use
ArrayList collection class to store objects of this Customer class.
import java.util.*;
class Customer
{
String name;
int balance;
int id;
//Costructor
Customer(String s, int i, int j)
{
name=s;
balance=i;
id=j;
}

//toString() method is overridden to give a meaningful String representaion of each object.


public String toString()
{
return "|Name : "+ name + "|Balance : "+ balance + "|ID : " + id + "|\n";
}

public static void main(String... ar)


{
ArrayList<Customer> arr= new ArrayList<Customer>(); //ArrayList will contain a collection
of Customer's objects.
//Creating Customer objects.
Customer customer1 = new Customer("Jay", 1000, 2);
Customer customer2 = new Customer("Shane", 7000 3);
Customer customer3 = new Customer("Ricky", 5000, 1);
Customer customer4 = new Customer("Tom", 3000, 6);
Customer customer5 = new Customer("Mick", 6000, 4);

//Storing objects in an ArrayList collection class.


arr.add(customer1);
arr.add(customer2);
arr.add(customer3);
arr.add(customer4);
arr.add(customer5);

for(Customer c : arr)
System.out.println(c);

}
}

Map Interface in Java


In Java, Map Interface is present in java.util package represents a mapping between a key
and a value. Java Map interface is not a subtype of the Collection interface. Therefore it
behaves a bit differently from the rest of the collection types. A map contains unique keys.
Maps are perfect to use for key-value association mapping such as dictionaries. The maps
are used to perform lookups by keys or when someone wants to retrieve and update
elements by keys. Some common scenarios are as follows:
• A map of error codes and their descriptions.
• A map of zip codes and cities.
• A map of managers and employees. Each manager (key) is associated with a list
of employees (value) he manages.
• A map of classes and students. Each class (key) is associated with a list of students
(value).

Creating Map Objects


Since Map is an interface, objects cannot be created of the type map. We always need a class
that extends this map in order to create an object. And also, after the introduction of Generics
in Java 1.5, it is possible to restrict the type of object that can be stored in the Map.
Syntax: Defining Type-safe Map

Map hm = new HashMap();


// Obj is the type of the object to be stored in Map

Characteristics of a Map Interface


1. A Map cannot contain duplicate keys and each key can map to at most one value.
Some implementations allow null key and null values like
the HashMap and LinkedHashMap, but some do not like the TreeMap.
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders,
while HashMap does not.
3. There are two interfaces for implementing Map in Java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap.
Methods in Java Map Interface
Method Action Performed

This method is used in Java Map Interface to clear and


clear() remove all of the elements or mappings from a specified
Map collection.

This method is used in Map Interface in Java to check


whether a particular key is being mapped into the Map or
containsKey(Object)
not. It takes the key element as a parameter and returns True
if that element is mapped in the map.

This method is used in Map Interface to check whether a


particular value is being mapped by a single or more than
containsValue(Object) one key in the Map. It takes the value as a parameter and
returns True if that value is mapped by any of the keys in
the map.

This method is used in Map Interface in Java to create a set


out of the same elements contained in the map. It basically
entrySet()
returns a set view of the map or we can create a new set and
store the map elements into them.

This method is used in Java Map Interface to check for


equality between two maps. It verifies whether the elements
equals(Object)
of one map passed as a parameter is equal to the elements of
this map or not.

This method is used to retrieve or fetch the value mapped by


get(Object) a particular key mentioned in the parameter. It returns
NULL when the map contains no such mapping for the key.
Method Action Performed

This method is used in Map Interface to generate a


hashCode()
hashCode for the given map containing keys and values.

This method is used to check if a map is having any entry


isEmpty() for key and value pairs. If no mapping exists, then this
returns true.

This method is used in Map Interface to return a Set view of


the keys contained in this map. The set is backed by the
keySet()
map, so changes to the map are reflected in the set, and
vice-versa.

This method is used in Java Map Interface to associate the


put(Object, Object)
specified value with the specified key in this map.

This method is used in Map Interface in Java to copy all of


putAll(Map)
the mappings from the specified map to this map.

This method is used in Map Interface to remove the


remove(Object)
mapping for a key from this map if it is present in the map.

This method is used to return the number of key/value pairs


size()
available in the map.

This method is used in Java Map Interface to create a


values() collection out of the values of the map. It basically returns a
Collection view of the values in the HashMap.

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 {

// Main driver method


public static void main(String args[])
{
// Creating an empty HashMap
Map<String, Integer> hm
= new HashMap<String, Integer>();
// Inserting pairs in above Map
// using put() method
hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));

// Traversing through Map using for-each loop


for (Map.Entry<String, Integer> me :
hm.entrySet()) {

// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}
Output:
a:100
b:200
c:300
d:400

You might also like