MCA Java Programming 12(2)
MCA Java Programming 12(2)
Names of Sub-Units
Collections Overview, Changes to Collections, The Collection Interfaces, The Collection Classes,
Accessing a collection via an Iterator, Storing User-Defined Classes in Collections, The Random Access
Interface, Working With Maps, Comparators, The Collection Algorithms, Why Generic Collections? The
legacy Classes and Interfaces
Overview
In this unit, we will take a look at the collections framework in Java, which are supported by java.
util package. As you can infer from the name, collection lets you group elements in various ways.
The collections framework provides various interfaces, classes and methods that make easier way of
working with items. These interfaces and classes are important, not just for their utility, but because
many other Java methods, use or return objects of these classes, such as the ArrayList and HashMap
classes.
Learning Objectives
Learning Outcomes
http://pages.di.unipi.it/corradini/Didattica/PR2-B-14/Java%20Collections%20Framework.pdf
12.1 INTRODUCTION
A collection is an object that organises multiple data items into a single group. In real-life scenarios, a
record of phone numbers that is required by you are kept in the mobile phonebook. You can also add
or remove a contact, or locate a contact, as per your requirement. Similarly, in Java while writing an
application, you may require to handle multiple interrelated data items. Therefore, the Java collections
framework is a standardised way wherein a group of objects is handled by programs.
Collections in Java are not type-safe in nature and thereby the concept of generics was introduced to
the evolution of Java 5. This unit discusses about collections, the creation of your own generic class and
methods, with the implementation of wildcards.
The collections framework defines several interfaces and classes provided under the java.util package.
The Collections API comprises numerous interfaces and concrete classes. The Collection interface (java.
util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection
classes.
2
UNIT 12: The Collections Framework JGI JAIN DEEMED-TO-BE UNIVERSIT Y
Iterable
Collection
e
Map extends
<Interface> I
List Queue Set Implement
3
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
store incompatible types in a collection accidentally due to which run-time type mismatch errors might
occur.
As generics allow you to explicitly state the type of data being stored, and therefore, run-time type
mismatch errors can be avoided. Although inclusion of generics has changed the declarations of most
of its classes and interfaces, and some of their methods, but, the Collections Framework still functions
the same as it did earlier to generics.
4
UNIT 12: The Collections Framework JGI JAINDEEMED-TO-BE UNIVERSIT Y
boolean equals(Object o) It compares the given object with this list for equality.
Object get(int index) It gets the element at the given position in this list.
int hashCode() It gets the hashcode value for this list.
int indexOf(Object o) It gets the index of the first occurrence of the given element in this
list or -1 if this list does not contain the element.
boolean isEmpty() It returns True if this list contains no elements.
Iterator iterator() It gets an iterator over the elements in this list in proper sequence.
int lastIndexOf(Object o) It gets the index of the last occurrence of the given element in this
list or -1 if this list does not contain the element.
ListIterator listIterator() It gets a list iterator over the elements in this list (in proper
sequence).
ListIterator listIterator It gets a list iterator of the elements in this list, starting at the given
(int index) position in this list.
Object remove(int index) It removes the element at the given position in this list.
boolean remove(Object o) It removes the first occurrence in this list of the given element.
boolean removeAll It removes from this list all of its elements that are contained in the
(Collection<?> c) given collection (optional operation).
5
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
E set(int index, E element) It replaces the element at the given position in the list with the new
element.
int size() It gets the number of elements in this list.
default void sort(Comparator<? super E> It sorts this list according to the order induced by the specified
c) Comparator.
default Spliterator<E> spliterator() It creates a Spliterator over the elements in this list.
List<E> subList(int fromIndex, int toIndex) It returns a view of the portion of this list between the specified
fromIndex, inclusive and toIndex, exclusive.
List subList(int fromIndex, int toIndex) It gets a view of the section between the given fromIndex (inclusive)
and toIndex.
Object[] toArray() It gets an array containing all the elements in this list in proper
sequence (from first to last element).
<T> T[] toArray It gets an array containing all the elements in this list in proper
(T[ ] a) sequence (from first to last element); the runtime type of the
returned array is that of the specified array.
boolean equals(Object o) It compares the given object with this set for equality.
int hashCode() It gets the hashcode value for this set.
boolean isEmpty() It returns True if this set contains no elements.
Iterator iterator() It gets an iterator over the elements in this set.
boolean remove(Object o) It removes the given element from this set if it is present.
6
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
int size() It gets the number of elements in this set (its cardinality).
Object[] toArray() It gets an array containing all the elements in this set.
<T> T[] toArray It gets an array containing all the elements in this set whose runtime
(T[ ] a) type is that of the given array.
SortedSet<E> tailSet It gets a view of the portion of this set whose elements are greater
(E fromElement) than or equal to fromElement.
7
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
8
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
You will find the constructor for the AbstractCollection class in Table 8 and its methods in Table 9:
boolean retainAll (Collection<?> c) It keeps only the elements contained in the given collection.
abstract int size() It gets the number of elements in this collection.
Object[] toArray() It gets an array containing all the elements in this collection.
<T> T[] toArray(T[ ] a) It gets an array that contains all the elements in this collection.
String toString() It gets a string representation of this collection.
10
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
E remove(int index) It removes the element at the given position in this list.
protected void removeRange It removes from this list all the elements whose index is between fromIndex
(int fromIndex, int and toIndex.
toIndex)
E set(int index, E element) It replaces the element at the given position in this list with the new
element.
List subList(int fromIndex, int It gets a view of the portion of this list between the specified fromIndex
toIndex) (inclusive) and toIndex (exclusive).
11
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
You will find the constructor of the AbstractSequentialList class in Table 13 and its methods in Table 14:
boolean addAll(int index, Collection<? It inserts all the elements in the given collection into this list at the
extends E> c) specified position (optional operation).
Object get(int index) It gets the element at the given position in this list.
Iterator<E> iterator() It gets an iterator over the elements in this list.
abstract ListIterator<E> It gets a list iterator over the elements in this list.
listIterator(int index)
E remove(int index) It removes the element at the given position in this list (optional
operation).
E set It replaces the element at the given position in this list with the
(int index, E element) specified element (optional operation).
12
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
boolean addAll It inserts all the elements in the given collection into this list, starting
(int index, Collection<? extends E> c) at the given position.
E remove(int index) It removes the element at the given position in this list.
boolean remove(Object elem) It removes the first occurrence of the specified element from this list,
if it is present.
protected void removeRange It removes from this list all the elements whose index is between
(int fromIndex, int toIndex) fromIndex and toIndex.
E set(int index, E element) It replaces the element at the given position in this list with the given
element.
int size() It gets the number of elements in this list.
void sort(Comparator<? super E> c) It sorts this list according to the order induced by the specified
Comparator.
Spliterator<E> spliterator() It creates a late-binding and fail-fast Spliterator over the elements in
this list.
List<E> subList(int fromIndex, int It returns a view of the portion of this list between the specified
toIndex) fromIndex, inclusive and toIndex, exclusive.
Object[] toArray() It gets an array containing all the elements in this list in proper
sequence(from first to last element).
<T> T[] toArray(T[] a) It gets an array containing all the elements in this list in proper
sequence(from first to last element); the runtime type of the returned
array is that of the specified array.
void trimToSize() It trims the capacity to be the list’s current size.
You can add elements to an ArrayList object with the add() method, get an element at a certain index
with the get() method, and remove elements with the remove() method. Let’s consider an example in
13
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
which we add elements to an array at runtime. Remember, we are using two forms of the add() method:
general form and the form that allows to add an element at a specific location(index). We are also using
the remove() method to remove one element. The Iterator interface is defined in the java.util package.
This Iterator interface has three methods—hasNext(), next() and remove(). These methods are all you
need to access each element of a collection, as you see in Program 1:
Program 1: Using the ArrayList Class
import java.util.*;
class Arraylist
{
public static void main(String args[])
{
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.add("C++");
arraylist.add("C#");
arraylist.add("JavaScript ");
arraylist.add("Python ");
arraylist.add("VB");
arraylist.add("R");
arraylist.add(1, "Java");
arraylist.remove("VB");
System.out.println(arraylist);
System.out.println("\nUsing the Iterator interface");
String s;
Iterator e = arraylist.iterator();
while (e.hasNext())
{
s = (String)e.next();
System.out.println(s);
}
}
}
Here’s the output of Program:
D:\Java folder\java Arraylist
Using the add method
[C++, Java,C#, JavaScript, Python, VB, R]
[C++, Java,C#, JavaScript, Python, R]
14
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Python
R
15
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
To build a linked list, you can use the add(), addFirst() and addLast() methods; to get an element at a
certain index, you can use the get(), getFirst() and getLast() methods; to set an element’s value, you can
use the set method; and to remove an element, you can use the remove(), removeFirst() and removeLast()
methods.
Program 2 demonstrates ArrayDeque by using it to create a stack:
Program 2: Using the ArrayDeque Class
import java.util.*;
class ArrayDequeDemo { public static void main(String args[])
{
ArrayDeque<String> arrdeque= new ArrayDeque<String>();
arrdeque.push("C++"); arrdeque.push("C#");
arrdeque.push("JavaScript");
arrdeque.push("VB");
16
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
arrdeque.push("VB");
arrdeque.push("R");
System.out.println("Popping the stack: ");
while (arrdeque.peek() != null)
{
System.out.println(arrdeque.pop() + " ");
}
System.out.println();
}
}
Here's the output of Program:
D:\Java folder\java ArrayDequeDemo
Popping the stack:
R
VB
Python
JavaScript
C#
C++
17
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
18
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
To build a linked list, you can use the add(), addFirst() and addLast() methods; to get an element at a
certain index, you can use the get(), getFirst() and getLast() methods; to set an element’s value, you
can use the set() method; and to remove an element, you can use the remove(), removeFirst(), and
removeLast() methods.
19
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Program 3 shows an example of HasSet in which we add elements to a set and then print out that set:
Program 3: Using the HashSet Class
import java.util.*;
class Hashset
{
public static void main(String args[])
{
HashSet<String> hashset1 = new HashSet<String>();
hashset1.add("C++");
hashset1.add("Java");
hashset1.add("C#");
hashset1.add("JavaScript");
hashset1.add("Python");
hashset1.add("VB");
hashset1.add("R");
System.out.println(hashset1);
}
}
Here’s the output of Program:
D:\Java folder\java Hashset
[C++, Python, JavaScript, C#, Java, R, VB]
One thing to note about hashes is that you can’t guarantee the order in which elements are stored
internally. In fact, when you print out this set, you can see that all elements are stored in exactly the
reverse order:
20
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
| java.util.AbstractSet
| java.util.TreeSet
You will find the constructors for the TreeSet class in Table 23 and its methods in Table 24:
21
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
The TreeSet class just implements a set using a tree for internal storage. A difference from the HashSet
class is that elements in a TreeSet object are stored in sorted order.
22
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
23
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Yogita
105638
6-78, Saharanpur Delhi 1853
Rajni
101264
Sector 9, Chandigarh Punjab 1820
24
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Similar to the Sets and Lists interfaces, the Maps also use the equals() method to verify whether two keys
are the same or not.
Java also derives some standard classes from these interfaces—the map classes.
You will also see other classes here that are not technically members of the collection framework—
Arrays, Vector, Stack, Hashtable and others. These older collections have been rebuilt on collection
framework functionality. In fact, most standard computing collections are implemented in Java in
various ways; for example, the TreeSet class implements a set using a tree internally, which means
access time is quick. HashSet implements a set using a hash internally, which means that adding and
removing elements from such a set should always take the same amount of time, no matter how large
the set grows.
25
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
26
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
You will find the constructors for the HashMap class in Table 29 and its methods in Table 30:
27
JGI JAIN DEEMED-TO-BE UNIVERSIT Y
Java Programming
The put() method is used to add a key/value pair to a map, and the get() method is used to retrieve
a value, given a key. For example, the string drink will be left holding the text “root beer” after this
example executes:
hashmap.put("drink", "root beer");
String drink = hashmap.get("drink");
You can also get a set corresponding to the map with the entrySet() method, and you can iterate over
that set using the Map.Entry interface.
K ceilingKey It returns the least key greater than or equal to the given key, or null if
(K key) there is no such key.
28
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
12.10 COMPARATORS
You can use a comparator to find the sorting order used in the TreeSet objects; for example, with the
implementation of the Comparator interface. The methods of this interface are provided in Table 33:
The compare() method compares two objects, obj1 and obj2, and returns -1 if obj1 is less than obj2; 0 if
they are equal; and 1 if obj1 is greater than obj2. By overriding this method, you can support a custom
sorting order.
Consider Program 5 in which we sort a TreeSet object in ascending order—except for one element,
JavaScript, which we always want to appear at the beginning of the set.
29
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
class ComparatorDemo
{
@SuppressWarnings("unchecked")
public static void main(String args[])
{
TreeSet<String> treeset = new TreeSet<String>(new
NewComparator());
treeset.add("C++");
treeset.add("Java");
treeset.add("C#");
treeset.add("JavaScript");
treeset.add("Python");
treeset.add("VB");
treeset.add("R");
Iterator iterator = treeset.iterator();
while(iterator.hasNext()) { System.out.println(iterator.
next()); }
}
}
class NewComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
if (((String) obj1).equals("JavaScript")) return -1;
return ((String) obj1).compareTo((String) obj2); }
}
Here’s the output of this example. Note that item at index 3 i.e.‘JavaScript’ comes first:
D:\Java folder\java ComparatorDemo
JavaScript
C++
Java
C#
Python
VB
R
30
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
The collections framework algorithms are polymorphic which means each algorithm can operate on
objects that implement specific interfaces, irrespective of the basic implementations.
The concept of generics was introduced in JDK 1.5 to overcome the problem of explicit typecasting.
It has also introduced some other exciting features. In the case of generic collection, Java allows the
programmer to create a collection which is type-safe and does not need explicit typecasting while
retrieving the objects from the collection. The following code snippet represents the generic type of
collection creation of the preceding code snippet:
List<Integer> objList=new LinkedList<Integer>();
objList.add(new Integer(0));
Integer var=objList.iterator().next();
31
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
In the preceding code snippet, the collection objList is created with a specified type Integer. According
to the preceding code snippet, Integer is a parameterised type or type parameter. The type parameter
intimates the compiler that the collection objList contains objects of only Integer data type. Now, no
other object type other than of Integer type can be assigned to the collection. An attempt to do this will
generate a compile-time error. In the case of generic collections, the compiler is aware of the type of
objects that are supposed to be added to the collection. Therefore, there is no need to explicitly typecast,
as shown in the preceding code snippet.
Another feature of generic collections is that you can define a method with the type parameter. Passing
the type parameter in a method makes the argument of the method type-safe. For example, the following
code snippet defines a method with the type parameter argument:
void addIntegerList(List<Integer> intobj) {
intobj.add(new Integer(25));
}
In the preceding code snippet, the addIntegerList method is defined with an argument intobj, which is
declared as a type parameter Integer. This parameter is type-safe now. If you try to add any object of
data type other than an Integer, a compile-time error will be generated. Consider the following code
snippet that will generate a compilation error:
void addIntegerList(List<Integer> intobj) {
intobj.add("Vikash");
}
In the preceding code snippet, in place of an Integer object a String object Vikash is added to the collection
intobj. It is illegal and generates a compilation error. The compilation error is generated because the
intobj collection is type-safe and only objects of the Integer type can be added to it.
Similar to the argument of a method, the return type of a method can also be made type-safe by
declaring its return type with type parameter. The following code snippet defines a method with the
type-safe return type:
List<Integer> getIntegerList() {
List<Integer> objList=new LinkedList<Integer>();
return objList;
}
In the preceding code snippet, the getIntegerList() method is defined, which returns a collection of
Integer type of objects. The return type of this method is type-safe. An attempt to return any other type
of collection object from this method will cause a compilation error. The following code snippet defines
a method that will generate a compilation error:
List<Integer> getIntegerList() {
List<String> strList=new ArrayList<String>();
return strList;
}
In the preceding code snippet, instead of returning an Integer type of collection a collection of type
String is returned from the method. This causes a compilation error because the return type of the
method is type-safe and it must return a collection of Integer type of objects only. An advantage of
making the return type of the method type-safe is that when this method is called explicit typecast of
the object to be returned from the method is not required. This is because the compiler is aware of the
type of the collection objects to be returned from the method.
32
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
The collection with which the concept of generic is implemented, that is, the type parameters are used
are called generic collections, whereas the collections created with the legacy style of code are called
non-generic collections. You can create a collection with the type parameter <Object>, which contains
any type of object similar to the non-generic collections. Although a collection with the type parameter
<Object> is similar to non-generic collections, it sometimes behaves differently. You will notice this
difference in the following sections in which generic classes and non-generic classes in the collections
are discussed.
So, you have the legacy code that uses java.io.File and would prefer taking benefit of the java.nio.file.
Path functionality with minimal impact on your code. The various legacy classes defined by java.util
package are:
Dictionary
Hashtable
Stack
Vector
Properties
The Java Native Interface is developed for using Java in order to encapsulate native legacy code on
small embedded platforms. We must know why existing technologies for encapsulating legacy code,
Java Native Interface (JNI), is not enough for an important range of small embedded platforms, and we
depict how the JNI provides previously missing functionality.
33
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
You will find the fields of the Vector class in Table 34, its constructors in Table 35, and its methods in
Table 36:
boolean addAll(int index, It inserts all the elements in the given collection into this vector at the
Collection c) given position.
void addElement(Object obj) It adds the given component to the end of this vector, increasing its size
by one.
int capacity() It gets the current capacity of this vector.
void clear() It removes all the elements from this vector.
Object clone() It gets a clone of this vector.
Object elementAt(int index) It gets the component at the given index.
Enumeration elements() It gets an enumeration of the components of this vector.
int indexOf(Object elem) It returns the index of the first occurrence of the given element. In this
vector, or -1 if this vector does not contain element.
int indexOf It searches for the first occurrence of the given argument, beginning the
(Object elem, int index) search at index.
void insertElementAt It inserts the given object as a component in this vector at the given index.
(Object obj, int index)
34
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Each vector has a capacity, which is the maximum size it can grow to. When you exceed that size, the
capacity is automatically increased. You can use the add() and addElement() methods to add elements
to a vector, the remove() and removeElement() methods to remove elements, and the contains() method
to do a search.
You use the push() method to add an element to a stack and the pop() method to retrieve it; note that
elements come off a stack in the reverse order in which they were added to it. Consider Program 6 in
which we push and then pop elements on a stack:
Program 6: Pushing and then popping elements on a stack
import java.util.*;
class StackDemo
{
public static void main(String args[])
{
35
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
}
catch (EmptyStackException e) { }
}
}
Here’s the output of this example:
D:\Java folder\java StackDemo
6
5
4
3
2
1
0
36
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
37
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
You store and retrieve key/value pairs in a hashtable using the put() and get() methods. You can get an
Enumeration object for the keys in a hashtable using the keys() method, and you can use that object to
loop over the elements of the hash.
38
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
void list(PrintStream out) It prints this property list to the given output stream.
void list(PrintWriter out) It prints this property list to the given writer stream.
void load It reads a property list from the input stream.
(InputStream inStream)
Enumeration propertyNames() It gets an enumeration of all the keys in this property list.
void save(OutputStream out, String It is deprecated and it uses the store method instead.
header)
Object setProperty It calls the hashtable method put.
(String key, String value)
void store It writes this property list in this Properties table to the output stream in
(OutputStream out, String a format acceptable for use with the load method.
header)
Set <String> It returns a set of keys in this property list where the key and its
stringPropertyNames() corresponding value are strings, including distinct keys in the default
property list if a key of the same name has not already been found from
the main properties list.
You can put property values into a Properties object with the setProperty() method, and you can get
property values with the getProperty() method. Consider program 7 in which we create a Properties
object, add property values to it, and then retrieve a property value. Note, in particular, that you can
supply a default value to getProperty() that it will return if there’s no property value matching the
property you have requested:
Program 7: Creating a Properties object, adding property values to it, and then retrieving a property
value
import java.util.*;
class PropertiesDemo
{
public static void main(String args[])
{
Properties properties1 = new Properties();
Set states; String outString;
properties1.setProperty("Property 0", "Value 0");
properties1.setProperty("Property 1", "Value 1");
properties1.setProperty("Property 2", "Value 2");
properties1.setProperty("Property 3", "Value 3");
properties1.setProperty("Property 4", "Value 4");
properties1.setProperty("Property 5", "Value 5");
properties1.setProperty("Property 6", "Value 6");
outString = properties1.getProperty("Property 3", "Missing");
39
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming
System.out.println(outString);
outString = properties1.getProperty("Property 7", "Missing");
System.out.println(outString);
}
}
Output of program 7:
D:\Java folder\java PropertiesDemo
Value 3
Missing
A collection is an object that organises multiple data items into a single group.
The collection framework provides a standardised way to handle a group of objects.
Collections store, retrieve and manipulate the collection of data items. Here, a collection of data
implies the formation of a natural group of data items, such as collection of cards, collection of
letters, collection of books, collections of contacts in your mobile phone.
The collections framework defines several interfaces and classes provided under the java.util
package.
Prior to Java 2, ad hoc classes, such as Dictionary, Vector Stack and Properties, were used to store
and manipulate groups of objects.
The Collection interface revolves around the objects to provide maximum generality. For example,
all general-purpose collection executions have a constructor that takes Collection parameter.
The List interface is the foundation of classes, such as LinkedList and ArrayList. It is basically an
extension of the Collection interface that stores the behaviour of a collection.
Sometimes you need to traverse the elements of a collection for some specific purpose, for instance
to display each element. To implement this, you need an iterator either using the Iterator interface
or using the ListIterator interface.
RandomAccess is an empty interface or called a marker interface.
A map is an object that stores associations between keys and values in pairs. It stores data in key/
value pairs, much like an array, where the indexes are, themselves, objects.
12.15 GLOSSARY
Collection: Refers to an object that organises multiple data items into a single group.
Collection framework: Provides a standardised way to handle a group of objects. Collections store,
retrieve and manipulate the collection of data items.
List interface: Refers to the foundation of classes, such as LinkedList and ArrayList.
Queue: Refers to a collection of elements to hold them before processing starts.
Set: Refers to a group of unique elements, and the HashSet class supports sets that use a hash
internally for storage.
40
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
https://www.logicbig.com/tutorials/core-java-tutorial/java-11-changes/collection-changes.html
Lab Exercises
Lab Exercise: Write a Java program to store a list of strings by implementing ArrayList and using
Iterator, traverse the elements of a list and display it on the console.
Solution:
import java.util.*;
class ArrayListDemo
{
public static void main(String args[]) 41
{
ArrayList<String> al=new ArrayList<String>();
al.add("Deepak");
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming
al.add("Chirag");
al.add("Divya");
al.add("Alice");
al.add("John");
al.add("Goransh");
al.add("Meenal");
Iterator<String> it = al.iterator();
while (it.hasNext())
{
System.out.print(it.next() + "\n");
}
}
}
Explanation
In this program, we have created object of the ArrayList class with the String parameter to make a
String type array list. Next, we have added items in the array list by using the add( ) method of the
ArrayList class. We have used the Iterator interface to fetch all the items from the array list with the help
of iterator() method of the ArrayList class. Finally, all the items are printed with the help of hasNext( )
method and while loop.
Output:
Deepak
Chirag
Divya
Alice
John
Goransh
Meenal
42