0% found this document useful (0 votes)
12 views43 pages

Unit 3 Part II

The document provides an overview of the Java Collection Framework, focusing on the Iterator and ListIterator interfaces for traversing collections. It explains the Map interface, its characteristics, and methods, along with examples of using HashMap and LinkedHashMap. Additionally, it highlights the differences between using for-each loops and iterators for accessing collection elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views43 pages

Unit 3 Part II

The document provides an overview of the Java Collection Framework, focusing on the Iterator and ListIterator interfaces for traversing collections. It explains the Map interface, its characteristics, and methods, along with examples of using HashMap and LinkedHashMap. Additionally, it highlights the differences between using for-each loops and iterators for accessing collection elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

The java collection framework often we want to cycle through the elements.

For example, we
might want to display each element of a collection. The java provides an
interface Iterator that is available inside the java.util package to cycle through each
element of a collection.
🔔 The Iterator allows us to move only forward direction.
🔔 The Iterator does not support the replacement and addition of new elements.
We use the following steps to access a collection of elements using the Iterator.

 Step - 1: Create an object of the Iterator by calling collection.itertor( ) method.


 Step - 2: Use the method hasNext( ) to access to check does the collection has the
next element. (Use a loop).
 Step - 3: Use the method next( ) to access each element from the collection. (use
inside the loop).

The Iterator has the following methods.

Method Description

Iterator iterator( ) Used to obtain an iterator to the start of the collection.

boolean hasNext( ) Returns true if the collection has the next element, otherwise, it return

E next( ) Returns the next element available in the collection.

Let's consider an example program to illustrate accessing elements of a collection via the
Iterator.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

TreeSet set = new TreeSet();

Random num = new Random();


for(int i = 0; i < 10; i++)
set.add(num.nextInt(100));
Iterator collection = set.iterator();

System.out.println("All the elements of TreeSet collection:");


while(collection.hasNext())
System.out.print(collection.next() + ", ");

}
}

Accessing a collection using for-each


We can use the for-each statement to access elements of a collection.
Let's consider an example program to illustrate accessing items from a collection using a for-
each statement.

Example
import java.util.*;

public class TreeSetExample {


public static void main(String[] args) {

TreeSet set = new TreeSet();


ArrayList list = new ArrayList();
PriorityQueue queue = new PriorityQueue();

Random num = new Random();


for(int i = 0; i < 10; i++) {
set.add(num.nextInt(100));
list.add(num.nextInt(100));
queue.add(num.nextInt(100));
}

System.out.println("\nAll the elements of TreeSet collection:");


for(Object element:set) {
System.out.print(element + ", ");
}

System.out.println("\n\nAll the elements of ArrayList collection:");


for(Object element:list) {
System.out.print(element + ", ");
}

System.out.println("\n\nAll the elements of PriorityQueue collection:");

for(Object element:queue) {
System.out.print(element + ", ");
}

}
}
The For-Each alternative
Using for-each, we can access the elements of a collection. But for-each can only be used if
we don't want to modify the contents of a collection, and we don't want any reverse access.
Alternatively, we can use the Iterator to access or cycle through a collection of elements.
Let's consider an example program to illustrate The for-each alternative.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

ArrayList list = new ArrayList();


PriorityQueue queue = new PriorityQueue();

Random num = new Random();


for(int i = 0; i < 10; i++) {
list.add(num.nextInt(100));
queue.add(num.nextInt(100));
}

// Accessing using for-each statement


System.out.println("\n\nAll the elements of ArrayList collection:");
for(Object element:list) {
System.out.print(element + ", ");
}

// Accessing using Iterator


Iterator collection = queue.iterator();
System.out.println("\n\nAll the elements of PriorityQueue collection:");

while(collection.hasNext()) {
System.out.print(collection.next() + ", ");
}

}
}

Accessing elements using ListIterator


The ListIterator interface is used to traverse through a list in both forward and backward
directions. It does not support all types of collections. It supports only the collection which
implements the List interface.
The ListIterator provides the following methods to traverse through a list of elements.

Method Description

ListIterator Used obtain an iterator of the list collection.


listIterator( )

boolean hasNext( ) Returns true if the list collection has next element, otherwise it return

E next( ) Returns the next element available in the list collection.

boolean hasPrevious( ) Returns true if the list collection has previous element, otherwise it re

E previous( ) Returns the previous element available in the list collection.

int nextIndex( ) Returns the index of the next element. If there is no next element, ret

E previousIndex( ) Returns the index of the previous element. If there is no previous elem

Let's consider an example program to illustrate ListIterator to access elements of a list.

Example
import java.util.*;

public class TreeSetExample {

public static void main(String[] args) {

ArrayList list = new ArrayList();

Random num = new Random();


for(int i = 0; i < 10; i++) {
list.add(num.nextInt(100));
}
// Accessing in forward direction using ListIterator
ListIterator collection = list.listIterator();
System.out.println("\n\nAll the elements of PriorityQueue collection:");

while(collection.hasNext()) {
System.out.print(collection.next() + ", ");
}

// Accessing in reverse direction using ListIterator


System.out.println("\n\neverse of the PriorityQueue collection:");
while(collection.hasPrevious()) {
System.out.print(collection.previous() + ", ");
}

}
}

Map Interface in Java





In Java, the Map Interface is part of the java.util package and represents a
mapping between a key and a value. The Java Map interface is not a subtype of
the Collections interface. So, it behaves differently from the rest of the collection
types.
Key Features:
 No Duplicates in Keys: Keys should be unique, but values can be
duplicated.
 Null Handling: It allows one null key in implementations
like HashMap and LinkedHashMap, and allows multiple null values in
most implementations.
 Thread-Safe Alternatives: Use ConcurrentHashMap for thread-safe
operations. Also, wrap an existing map
using Collections.synchronizedMap() for synchronized access.
The Map data structure in Java is implemented by two interfaces:
 Map Interface
 SortedMap Interface
The three primary classes that implement these interfaces are,
 HashMap
 TreeMap
 LinkedHashMap
Now, let us go through a simple example first to understand the concept.
Example:

// Java Program Implementing HashMap


2

import java.util.HashMap;
3

import java.util.Map;
4

public class Geeks {


6

public static void main(String[] args) {


7

// Create a Map using HashMap


9
Map<String, Integer> m = new HashMap<>();
10

11

// Adding key-value pairs to the map


12

m.put("Geek1", 1);
13

m.put("Geek2", 2);
14

m.put("Geek3", 3);
15

16

System.out.println("Map elements: " + m);


17

}
18

Output
Map elements: {Geek3=3, Geek2=2, Geek1=1}

We must know that why and when to use Maps.


Maps are perfect to use for key-value mapping such as dictionaries. 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<String, Integer> hm = new HashMap<>(); // Type-safe map storing String
keys and Integer values
Characteristics of a Map Interface
 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.
 The order of a map depends on the specific implementations. For example,
TreeMap and LinkedHashMap have predictable orders, while HashMap does
not.
Methods in Java Map Interface
Methods Action Performed

This method is used in Java Map Interface to clear and remove all of the
clear()
elements or mappings from a specified Map collection.

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

containsValue(Object) This method is used in Map Interface to check whether a particular value is
being mapped by a single or more than one key in the Map. It takes the value
Methods Action Performed

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
entrySet() elements contained in the map. It basically 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
equals(Object) maps. It verifies whether the elements 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 a particular key
get(Object) mentioned in the parameter. It returns NULL when the map contains no such
mapping for the key.

This method is used in Map Interface to generate a hashCode for the given
hashCode()
map containing keys and values.

This method is used to check if a map is having any entry for key and value
isEmpty()
pairs. If no mapping exists, then this returns true.

This method is used in Map Interface to return a Set view of the keys
keySet() contained in this map. The set is backed by the 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 specified value
put(Object, Object)
with the specified key in this map.

This method is used in Map Interface in Java to copy all of the mappings from
putAll(Map)
the specified map to this map.

This method is used in Map Interface to remove the mapping for a key from
remove(Object)
this map if it is present in the map.
Methods Action Performed

This method is used to return the number of key/value pairs available in the
size()
map.

This method is used in Java Map Interface to create a collection out of the
values() values of the map. It basically returns a Collection view of the values in the
HashMap.

getOrDefault(Object key, V Returns the value to which the specified key is mapped, or defaultValue if this
defaultValue) map contains no mapping for the key.

merge(K key, V value,


BiFunction<? super V,? If the specified key is not already associated with a value or is associated with
super V,? extends V> null, associate it with the given non-null value.
remappingFunction)

If the specified key is not already associated with a value (or is mapped to
putIfAbsent(K key, V value) null) associates it with the given value and returns null, else returns the
current associate value.

Example:

// Java Program to Demonstrate


2

// Working of Map interface


3

// Importing required classes


5

import java.util.*;
6
7

// Main class
8

class Geeks {
9

10

// Main driver method


11

public static void main(String args[])


12

{
13

// Creating an empty HashMap


14

Map<String, Integer> hm
15

= new HashMap<String, Integer>();


16

17

// Inserting pairs in above Map


18

// using put() method


19

hm.put("a", new Integer(100));


20

hm.put("b", new Integer(200));


21

hm.put("c", new Integer(300));


22

hm.put("d", new Integer(400));


23

24

// Traversing through Map using for-each loop


25

for (Map.Entry<String, Integer> me :


26

hm.entrySet()) {
27
28

System.out.print(me.getKey() + ":");
29

System.out.println(me.getValue());
30

}
31

}
32

Output
a:100
b:200
c:300
d:400

Hierarchy of Map Interface in Java


Classes that implement the Map interface are shown in the below:
1. HashMap
HashMap is a part of Java’s collection since Java 1.2. It provides the basic
implementation of the Map interface of Java. It stores the data in (Key, Value)
pairs. To access a value one must know its key. This class uses a technique
called Hashing. Hashing is a technique of converting a large String to a small
String that represents the same String. A shorter value helps in indexing and faster
searches. Let’s see how to create a map object using this class.
Example:

// Java Program to illustrate the Hashmap Class


2

// Importing required classes


4

import java.util.*;
5

// Main class
7

public class Geeks {


8

// Main driver method


10

public static void main(String[] args)


11

{
12

13

// Creating an empty HashMap


14

Map<String, Integer> m = new HashMap<>();


15
16

// Inserting entries in the Map


17

// using put() method


18

m.put("Sweta", 10);
19

m.put("Amiya", 30);
20

m.put("Gudly", 20);
21

22

// Iterating over Map


23

for (Map.Entry<String, Integer> e : m.entrySet())


24

25

System.out.println(e.getKey() + " "


26

+ e.getValue());
27

}
28

Output
Amiya 30
Sweta 10
Gudly 20

2. LinkedHashMap
LinkedHashMap is just like HashMap with the additional feature of maintaining an
order of elements inserted into it. HashMap provided the advantage of quick
insertion, search, and deletion but it never maintained the track and order of
insertion which the LinkedHashMap provides where the elements can be accessed
in their insertion order. Let’s see how to create a map object using this class.
Example:
1

// Java Program to Illustrate the LinkedHashmap Class


2

import java.util.*;
3

public class Geeks {


5

public static void main(String[] args)


7

{
8

// Creating an empty LinkedHashMap


10

Map<String, Integer> m = new LinkedHashMap<>();


11

12

// Inserting pair entries in above Map


13

// using put() method


14

m.put("Sweta", 10);
15

m.put("Amiya", 30);
16

m.put("Gusly", 20);
17

18

// Iterating over Map


19
for (Map.Entry<String, Integer> e : m.entrySet())
20

21

// Printing key-value pairs


22

System.out.println(e.getKey() + " "


23

+ e.getValue());
24

}
25

Output
Sweta 10
Amiya 30
Gusly 20

3. TreeMap
The TreeMap in Java is used to implement the Map interface
and NavigableMap along with the Abstract Class. The map is sorted according
to the natural ordering of its keys, or by a Comparator provided at map creation
time, depending on which constructor is used. This proves to be an efficient way of
sorting and storing the key-value pairs. The ordering maintained by the TreeMap
must be consistent with the equals() method if a custom comparator is not used.
Example:

// Java Program to Illustrate TreeMap Class


2

// Importing required classes


4

import java.util.*;
5
6

// Main class
7

public class Geeks {


8

// Main driver method


10

public static void main(String[] args)


11

{
12

13

// Creating an empty TreeMap


14

Map<String, Integer> m = new TreeMap<>();


15

16

// Inserting custom elements in the Map


17

// using put() method


18

m.put("Sweta", 10);
19

m.put("Amiya", 30);
20

m.put("Gudly", 20);
21

22

// Iterating over Map using for each loop


23

for (Map.Entry<String, Integer> e : m.entrySet())


24

25

System.out.println(e.getKey() + " "


26
+ e.getValue());
27

}
28

Output
Amiya 30
Gudly 20
Sweta 10

Performing Different Operations using Map Interface and HashMap Class


Now, let’s see how to perform a few frequently used operations on a Map using the
widely used HashMap class.
1. Adding Elements
To add an element to the map, we can use the put() method. The insertion order is
not retained in the hashmap. Internally, for every element, a separate hash is
generated and the elements are indexed based on this hash to make it more
efficient.
Example:

// Java program to demonstrate


2

// the working of Map interface


3

import java.util.*;
4

class Geeks {
6

public static void main(String args[])


7

{
8

// Default Initialization of a
9
// Map
10

Map<Integer, String> hm1 = new HashMap<>();


11

12

// Initialization of a Map
13

// using Generics
14

Map<Integer, String> hm2


15

= new HashMap<Integer, String>();


16

17

// Inserting the Elements


18

hm1.put(1, "Geeks");
19

hm1.put(2, "For");
20

hm1.put(3, "Geeks");
21

22

hm2.put(new Integer(1), "Geeks");


23

hm2.put(new Integer(2), "For");


24

hm2.put(new Integer(3), "Geeks");


25

26

System.out.println(hm1);
27

System.out.println(hm2);
28

}
29

}
Output
{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

2. Changing Element
After adding the elements if we wish to change the element, it can be done by
again adding the element with the put() method. The elements in the map are
indexed using the keys, the value of the key can be changed by simply inserting
the updated value for the key for which we want to change.
Example:

// Java program to demonstrate


2

// the working of Map interface


3

import java.util.*;
4

class Geeks {
6

public static void main(String args[])


7

{
8

// Initialization of a Map
10

// using Generics
11

Map<Integer, String> hm1


12

= new HashMap<Integer, String>();


13
14

// Inserting the Elements


15

hm1.put(new Integer(1), "Geeks");


16

hm1.put(new Integer(2), "Geeks");


17

hm1.put(new Integer(3), "Geeks");


18

19

System.out.println("Initial Map: " + hm1);


20

21

hm1.put(new Integer(2), "For");


22

23

System.out.println("Updated Map: " + hm1);


24

}
25

Output
Initial Map: {1=Geeks, 2=Geeks, 3=Geeks}
Updated Map: {1=Geeks, 2=For, 3=Geeks}

3. Removing Elements
To remove an element from the Map, we can use the remove() method. This
method takes the key value and removes the mapping for a key from this map if it
is present in the map.
Example:

// Java program to demonstrate


2
// the working of Map interface
3

import java.util.*;
4

class Geeks {
6

public static void main(String args[])


8

{
9

10

// Initialization of a Map
11

// using Generics
12

Map<Integer, String> hm1


13

= new HashMap<Integer, String>();


14

15

// Inserting the Elements


16

hm1.put(new Integer(1), "Geeks");


17

hm1.put(new Integer(2), "For");


18

hm1.put(new Integer(3), "Geeks");


19

hm1.put(new Integer(4), "For");


20

21

System.out.println(hm1);
22
23

hm1.remove(new Integer(4));
24

25

System.out.println(hm1);
26

}
27

Output
{1=Geeks, 2=For, 3=Geeks, 4=For}
{1=Geeks, 2=For, 3=Geeks}

4. Iterating through the Map


There are multiple ways to iterate through the Map. The most famous way is to use
a for-each loop and get the keys. The value of the key is found by using
the getValue() method.
Example:

// Java program to demonstrate


2

// the working of Map interface


3

import java.util.*;
4

class Geeks {
6

public static void main(String args[])


7

{
8

9
// Initialization of a Map
10

// using Generics
11

Map<Integer, String> hm1


12

= new HashMap<Integer, String>();


13

14

// Inserting the Elements


15

hm1.put(new Integer(1), "Geeks");


16

hm1.put(new Integer(2), "For");


17

hm1.put(new Integer(3), "Geeks");


18

19

for (Map.Entry mapElement : hm1.entrySet()) {


20

int key = (int)mapElement.getKey();


21

22

// Finding the value


23

String value = (String)mapElement.getValue();


24

25

System.out.println(key + " : " + value);


26

}
27

}
28

Output
1 : Geeks
2 : For
3 : Geeks

Example: Count the Occurrence of Numbers using Hashmap


In this example, we are using putIfAbsent() along
with Collections.frequency() to count the exact occurrence of numbers. In many
programs, you need to count the occurrence of a particular number or letter. You
use the following approach to solve those types of problems.
Example:

// Java program to Count the Occurrence


2

// of numbers using Hashmap


3

import java.util.*;
4

class Geeks {
6

public static void main(String[] args)


7

{
8

int a[] = { 1, 13, 4, 1, 41, 31, 31, 4, 13, 2 };


9

10

// put all elements in arraylist


11

ArrayList<Integer> al = new ArrayList();


12

for (int i = 0; i < a.length; i++) {


13

al.add(a[i]);
14
}
15

16

HashMap<Integer, Integer> hm = new HashMap();


17

18

// counting occurrence of numbers


19

for (int i = 0; i < al.size(); i++) {


20

hm.putIfAbsent(al.get(i), Collections.frequency(
21

al, al.get(i)));
22

}
23

System.out.println(hm);
24

}
25

Output
{1=2, 2=1, 4=2, 41=1, 13=2, 31=2}

Legacy Classes - Java Collections


Early version of java did not include the Collections framework. It only
defined several classes and interfaces that provide methods for storing
objects. When Collections framework were added in J2SE 1.2, the original
classes were reengineered to support the collection interface. These
classes are also known as Legacy classes. All legacy classes and interface
were redesign by JDK 5 to support Generics. In general, the legacy classes
are supported because there is still some code that uses them.

The following are the legacy classes defined by java.util package

1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
There is only one legacy interface called Enumeration

NOTE: All the legacy classes are synchronized

Enumeration interface

1. Enumeration interface defines method to enumerate(obtain one at a


time) through collection of objects.
2. This interface is superseded(replaced) by Iterator interface.
3. However, some legacy classes such
as Vector and Properties defines several method in
which Enumeration interface is used.
4. It specifies the following two methods

boolean hasMoreElements() //It returns true while there


are still more elements to extract,

and returns false when all the elements have been


enumerated.

Object nextElement() //It returns the next object in the


enumeration i.e. each call to nextElement() method

obtains the next object in the enumeration. It throws


NoSuchElementException when the

enumeration is complete.
Vector class

1. Vector is similar to ArrayList which represents a dynamic array.


2. There are two differences between Vector and ArrayList. First,
Vector is synchronized while ArrayList is not, and Second, it contains
many legacy methods that are not part of the Collections Framework.
3. With the release of JDK 5, Vector also implements Iterable. This
means that Vector is fully compatible with collections, and a Vector
can have its contents iterated by the for-each loop.
4. Vector class has following four constructor

5. Vector() //This creates a default vector, which has an


initial size of 10.

6.

7. Vector(int size) //This creates a vector whose initial


capacity is specified by size.

8.

9. Vector(int size, int incr) //This creates a vector whose


initial capacity is specified by size and whose

10.increment is specified by incr. The increment specifies


the number of elements to allocate each time

11.when a vector is resized for addition of objects.

12.

Vector(Collection c) //This creates a vector that contains


the elements of collection c.

Vector defines several legacy methods. Lets see some important legacy
methods defined by Vector class.

Method Description
void addElement(E element) adds element to the Vector

E elementAt(int index) returns the element at specified index

Enumeration elements() returns an enumeration of element in vector

E firstElement() returns first element in the Vector

E lastElement() returns last element in the Vector

void removeAllElements() removes all elements of the Vector

Example of Vector

import java.util.*;

public class Test

public static void main(String[] args)

Vector<Integer> ve = new Vector<Integer>();

ve.add(10);

ve.add(20);

ve.add(30);
ve.add(40);

ve.add(50);

ve.add(60);

Enumeration<Integer> en = ve.elements();

while(en.hasMoreElements())

System.out.println(en.nextElement());

10

20

30

40

50

60

Hashtable class

1. Like HashMap, Hashtable also stores key/value pair. However


neither keys nor values can be null.
2. There is one more difference between HashMap and Hashtable that
is Hashtable is synchronized while HashMap is not.
3. Hashtable has following four constructor

4. Hashtable() //This is the default constructor. The


default size is 11.

5.

6. Hashtable(int size) //This creates a hash table that has


an initial size specified by size.

7.

8. Hashtable(int size, float fillratio) //This creates a


hash table that has an initial size specified by size

9. and a fill ratio specified by fillRatio. This ratio must


be between 0.0 and 1.0, and it determines how full

10.the hash table can be before it is resized upward.


Specifically, when the number of elements is greater

11.than the capacity of the hash table multiplied by its


fill ratio, the hash table is expanded.

12.If you do not specify a fill ratio, then 0.75 is used.

13.

14.Hashtable(Map< ? extends K, ? extends V> m) //This


creates a hash table that is initialized with the

15.elements in m. The capacity of the hash table is set to


twice the number of elements in m.

The default load factor of 0.75 is used.

Example of Hashtable
import java.util.*;

class HashTableDemo

public static void main(String args[])

Hashtable<String,Integer> ht = new
Hashtable<String,Integer>();

ht.put("a",new Integer(100));

ht.put("b",new Integer(200));

ht.put("c",new Integer(300));

ht.put("d",new Integer(400));

Set st = ht.entrySet();

Iterator itr=st.iterator();

while(itr.hasNext())

Map.Entry m=(Map.Entry)itr.next();

System.out.println(itr.getKey()+" "+itr.getValue());

}
a 100

b 200

c 300

d 400

Difference between HashMap and Hashtable

Hashtable HashMap

Hashtable class is synchronized. HashMap is not synchronized.

Because of Thread-safe, Hashtable is


HashMap works faster.
slower than HashMap

Neither key nor values can be null Both key and values can be null

Order of table remain constant over does not guarantee that order of map
time. remain constant over time.

Stack class

1. Stack class extends Vector.


2. It follows last-in, first-out principle for the stack elements.
3. It defines only one default constructor

Stack() //This creates an empty stack

4. If you want to put an object on the top of the stack, call push()
method. If you want to remove and return the top element, call pop()
method. An EmptyStackException is thrown if you call pop() method
when the invoking stack is empty.
You can use peek() method to return, but not remove, the top object. The
empty() method returns true if nothing is on the stack. The search()
method determines whether an object exists on the stack and returns the
number of pops that are required to bring it to the top of the stack.

Example of Stack

import java.util.*;

class StackDemo {

public static void main(String args[]) {

Stack st = new Stack();

st.push(11);

st.push(22);

st.push(33);

st.push(44);

st.push(55);

Enumeration e1 = st.elements();

while(e1.hasMoreElements())

System.out.print(e1.nextElement()+" ");
st.pop();

st.pop();

System.out.println("\nAfter popping out two elements");

Enumeration e2 = st.elements();

while(e2.hasMoreElements())

System.out.print(e2.nextElement()+" ");

11 22 33 44 55

After popping out two elements

11 22 33

Dictionary class

1. Dictionary is an abstract class.


2. It represents a key/value pair and operates much like Map.
3. Although it is not currently deprecated, Dictionary is classified as
obsolete, because it is fully superseded by Map class.
Enumeration Interface In Java



java.util.Enumeration interface is one of the predefined interfaces, whose object
is used for retrieving the data from collections framework
variable( like Stack, Vector, HashTable etc.) in a forward direction only and not in
the backward direction. This interface has been superceded by an iterator.
The Enumeration Interface defines the functions by which we can enumerate the
elements in a collection of elements. For new code, Enumeration is considered
obsolete. However, several methods of the legacy classes such as vectors and
properties, several API classes, application codes use this Enumeration interface.
Important Features
 Enumeration is Synchronized.
 It does not support adding, removing, or replacing elements.
 Elements of legacy Collections can be accessed in a forward direction
using Enumeration.
 Legacy classes have methods to work with enumeration and returns
Enumeration objects.
Declaration
public interface Enumeration<E>
Where E is the type of elements stored in a Collection.
The sub-interfaces of Enumeration interface is NamingEnumeration and
implementing class is StringTokenizer.
Creating Enumeration Object
Vector ve = new Vector();
Enumeration e = v.elements();
Example:
 Java
// Java program to test Enumeration

import java.util.Vector;

import java.util.Enumeration;

public class EnumerationClass {

public static void main(String args[])

Enumeration months;

Vector<String> monthNames = new Vector<>();


monthNames.add("January");

monthNames.add("February");

monthNames.add("March");

monthNames.add("April");

monthNames.add("May");

monthNames.add("June");

monthNames.add("July");

monthNames.add("August");

monthNames.add("September");

monthNames.add("October");

monthNames.add("November");

monthNames.add("December");

months = monthNames.elements();

while (months.hasMoreElements()) {

System.out.println(months.nextElement());

Output
January
February
March
April
May
June
July
August
September
October
November
December
Java Enumeration Interface With SequenceInputStream
 Java
import java.io.*;

import java.util.*;

class GFG {

public static void main(String args[])

throws IOException

// creating the FileInputStream objects for all the

// files

FileInputStream fin

= new FileInputStream("file1.txt");

FileInputStream fin2

= new FileInputStream("file2.txt");

FileInputStream fin3

= new FileInputStream("file3.txt");

FileInputStream fin4

= new FileInputStream("file4.txt");

// creating Vector object to all the stream

Vector v = new Vector();

v.add(fin);

v.add(fin2);

v.add(fin3);

v.add(fin4);

// creating enumeration object by calling the

// elements method

Enumeration e = v.elements();

// passing the enumeration object in the constructor

SequenceInputStream bin

= new SequenceInputStream(e);
int i = 0;

while ((i = bin.read()) != -1) {

System.out.print((char)i);

bin.close();

fin.close();

fin2.close();

Creation Of Custom Enumeration


 Java
import java.util.Enumeration;

import java.lang.reflect.Array;

public class EnumerationClass implements Enumeration {

private int size;

private int cursor;

private final Object array;

public EnumerationClass(Object obj)

Class type = obj.getClass();

if (!type.isArray()) {

throw new IllegalArgumentException(

"Invalid type: " + type);

size = Array.getLength(obj);

array = obj;

public boolean hasMoreElements()

return (cursor < size);

}
public object nextElements()

return Array.get(array, cursor++);

Creation of Java Enumeration using String Array


 Java
import java.util.*;

import java.io.*;

public class EnumerationExample {

public static void main(String args[])

// String Array Creation

String str[] = { "apple", "facebook", "google" };

// Array Enumeration Creation

ArrayEnumeration aenum = new ArrayEnumeration(str);

// usageof array enumeration

while (aenum.hasMoreElements()) {

System.out.println(aenum.nextElement());

Methods Of Enumeration Interface

 E – type of elements
Modifier
And Type Method Explanation

default This method returns an Iterator which traverses all


asIterator()
Iterator<E> the remaining elements covered by this enumeration.

On implementation, it returns the boolean value if


boolean hasMoreElements() there are more elements to extract or not and returns
false when all the elements have been enumerated.

This method returns the next element of the


enumeration. It
E nextElement()
throws NoSuchElementException when there are no
more elements.

You might also like