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

Collection Framework Module 02

The document provides an overview of the Java Collections Framework, which was introduced in J2SE 1.2 to facilitate the storage and manipulation of groups of objects. It covers various collection types such as List, Set, and Map, along with their interfaces and implementations, as well as recent enhancements like generics and autoboxing. Additionally, it discusses key methods in the Collection interface, the use of iterators, and specific collection classes like HashSet and TreeSet.

Uploaded by

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

Collection Framework Module 02

The document provides an overview of the Java Collections Framework, which was introduced in J2SE 1.2 to facilitate the storage and manipulation of groups of objects. It covers various collection types such as List, Set, and Map, along with their interfaces and implementations, as well as recent enhancements like generics and autoboxing. Additionally, it discusses key methods in the Collection interface, the use of iterators, and specific collection classes like HashSet and TreeSet.

Uploaded by

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

Java Collections

Framework
Santhosh SG
Module-2
Collections Overview, Recent 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, Parting Thoughts on Collections.
Collections
• Collections framework was not a part of original Java release. Collections were
added to J2SE 1.2. Prior to Java 2.
• A collection in java is a framework that provides architecture to store and
manipulate the group of objects.
• All the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion etc. can be performed by Java Collections.
• Java Collection simply means a single unit of objects.
• Java Collection framework provides many interfaces (Set, List, Queue, Deque
etc.) and classes (ArrayList, LinkedHashSet, TreeSet etc). Vector, LinkedList,
PriorityQueue, HashSet,
• Framework in java means hierarchy of classes and interfaces.
• Collections framework is contained in java.util package.
The Java Collections Framework
• A collection — sometimes called a container — is simply an object that groups
multiple elements into a single unit.
• Collections are used to store, retrieve, manipulate, and communicate aggregate
data.
• Typically, they represent data items that form a natural group, such as
• a poker hand (a collection of cards),
• a mail folder (a collection of letters), or
• a telephone directory (a mapping of names to phone numbers).
A collections framework is a unified architecture for representing and manipulating collections.
All collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be
manipulated independently of the details of their representation. In object-oriented languages,
interfaces generally form a hierarchy.

Implementations: These are the concrete implementations of the collection interfaces. In essence,
they are reusable data structures.

Algorithms: These are the methods that perform useful computations, such as searching and sorting,
on objects that implement collection interfaces.
The algorithms are said to be polymorphic: that is, the same method can be used on many different
implementations of the appropriate collection interface. In essence, algorithms are reusable
functionality.
The Java Collections Framework
• An array is a very useful type in Java but it has its restrictions:
• once an array is created it must be sized, and this size is fixed;
• it contains no useful pre-defined methods.
• Java comes with a group of generic collection classes that grow as more elements
are added to them, and these classes provide lots of useful methods.
• This group of collection classes are referred to as the Java Collections Framework.
• The classes in the JCF are all found in the java.util package.
• Three important interfaces from this group are:
• List;
• Set;
• Map.
Hierarchy of Collection Framework
Let us see the hierarchy of Collection framework. The java.util package contains all the classes and
interfaces for the Collection framework.
Types of Collection
• Java supplies several types of Collection:
• Set: cannot contain duplicate elements, order is not important
• SortedSet: like a Set, but order is important
• List: may contain duplicate elements, order is important

• Java also supplies some “collection-like” things:


• Map: a “dictionary” that associates keys with values, order is not important
• SortedMap: like a Map, but order is important

• While you can get all the details from the Java API, you are expected to
learn (i.e. memorize):
• The signatures of the “most important” methods in each interface
• The most important implementations of each interface
The Collections hierarchy
The Collection Interface

The Collection interface is the interface which is implemented by all the


classes in the collection framework. It declares the methods that every
collection will have. In other words, we can say that the Collection interface
builds the foundation on which the collection framework depends.
Some of the methods of Collection interface are Boolean
• add (Objectobj),
• Boolean addAll (Collection c),
• void clear(), etc.

which are implemented by all the subclasses of Collection interface.


List the Collection Interfaces
List interface is the child interface of Collection interface. It inhibits a list type data structure in
which we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
Give the syntax of collection interface. Explain the methods present in collection
interface.

interface Collection<E>

E specifies the type of objects that the collection.


Collection extends the Iterable interface.
Iterating through the list cane be done through the iteratable interface.
Methods in collection interface

1. add
boolean add(E obj )
adds obj to the invoking collection.
Returns true if obj was added to the collection.
Returns false if obj is already a member of the collection and the collection does not allow duplicates.
2. addAll
boolean addAll(Collection<? extends E> c )
Adds all the elements of c to the invoking collection.
Returns true if the operation succeeded (i.e., the elements were added). Otherwise, returns false.

3. clear
void clear( )
Removes all elements from the invoking collection.
4. contains
boolean contains(Object obj )
Returns true if obj is an element of the invoking collection.
Otherwise, returns false.
5. containsAll
boolean containsAll(Collection<?> c )
Returns true if the invoking collection contains all elements of c.
Otherwise, returns false.
6. equals
boolean equals(Object obj )
Returns true if the invoking collection and obj are equal.
Otherwise, returns false.
7. hashCode
int hashCode( ) Returns the hash code for the invoking collection.
8. isEmpty
boolean isEmpty( )
Returns true if the invoking collection is empty.
Otherwise, returns false
9. iterator
Iterator<E> iterator( ) Returns an iterator for the invoking collection.
boolean remove(Object obj ) Removes one instance of obj from the invoking collection.
Returns true if the element was removed. Otherwise, returns false.
10. removeAll
boolean removeAll(Collection c ) Removes all elements of c from the invoking collection.
Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false.
11. retainAll
boolean retainAll(Collection c ) Removes all elements from the invoking collection except those
in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false.
12. size
int size( ) Returns the number of elements held in the invoking collection.
13. toArray
Object[ ] toArray( )
Returns an array that contains all the elements stored in the invoking collection.
The array elements are copies of the collection elements.
The array elements are copies of the collection elements.
If the size of array equals the number of elements, these are returned in array.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as
follows:
 Recently, the Collections Framework underwent a fundamental change
Recent Changes to Collections
that significantly increased its power and streamlined its use.
 The changes were caused by the
 addition of generics,
 autoboxing/unboxing, and
 the for-each style for loop, by JDK5

Why Collections were made Generic ?

 Generics added type safety to Collection framework.


 Earlier collections stored Object class references which meant any collection could store any
type of object.
 Hence there were chances of storing incompatible types in a collection, which could result in
run time mismatch. Hence Generics was introduced through which you can explicitly state the
type of object being stored
Collections and Autoboxing
We have studied that Autoboxing converts primitive types into Wrapper class
Objects. As collections doesn't store primitive data types(stores only refrences),
hence Autoboxing facilitates the storing of primitive data types in collection by
boxing it into its wrapper type
Using for-each loop
 for-each version of for loop can also be used for traversing each element of a collection.
 But this can only be used if we don't want to modify the contents of a collection and we don't
want any reverse access.
 for-each loop can cycle through any collection of object that implements Iterable interface.
import java.util.ArrayList;
Collection Creation:
public class ForEachExample { •An ArrayList<String> named languages is created to store a list of
public static void main(String[] args) {
// Creating an ArrayList of Strings programming languages.
ArrayList<String> languages = new ArrayList<>();
Adding Elements:
// Adding elements to the collection •The add() method is used to insert elements into the
languages.add("Java");
languages.add("Python"); ArrayList.Using for-each Loop:
languages.add("C++");
languages.add("JavaScript"); The for-each loop:
• (for (String lang :languages)) is used to iterate over the
// Using for-each loop to traverse the collection
System.out.println("Programming Languages:"); collection.It automatically retrieves each element one by one
for (String lang : languages) {
System.out.println(lang); without needing an explicit index.
} Printing Elements:
}
} OUTPUT: •Each element of the collection is printed in the loop.
Programming Languages:
Java Advantages of for-each Loop:
Python •Simplicity: No need to manage index or use .get() method.
C++ •Readability: The syntax is clear and easy to understand.
JavaScript •Avoids Errors: Reduces chances of IndexOutOfBoundsException.
Collection Interfaces
In Java, the Collection interface is part of the Java Collections Framework (JCF) and is the root
interface for most collection classes. It defines the basic operations for managing a group of
objects, such as adding, removing, and iterating over elements.
Collection (Root Interface)

├── List (Ordered, Duplicates Allowed)
│ ├── ArrayList
│ ├── LinkedList
│ ├── Vector (Thread-safe)
│ └── Stack (LIFO)

├── Set (Unique Elements, Unordered)
│ ├── HashSet
│ ├── LinkedHashSet (Insertion Order
Maintained)
│ └── TreeSet (Sorted Order)

└── Queue (FIFO, Ordered)
├── PriorityQueue (Natural Ordering)
├── ArrayDeque (Double-ended Queue)
└── LinkedList (Also Implements Queue)
All these Interfaces give several methods which are defined by collections classes which implement these
interfaces
Most commonly thrown Exceptions in Collections Framework
HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a collection that
uses a hash table for storage.
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
o HashSet stores the elements by using a mechanism called hashing.
o HashSet contains unique elements only.
HashSet is a generic class that has this declaration:
class HashSet<E>
Here, E specifies the type of objects that the set will hold.
Constructor
HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
import java.util.*; Explanation:
class HashSetDemo { 1.HashSet<String> hs = new HashSet<String>();
public static void main(String args[]) { •A HashSet is created to store string values.
HashSet<String> hs = new HashSet<String>();
•HashSet is an unordered collection of unique elements.
// Adding elements to HashSet 2.Adding elements using add() method
hs.add("B"); •Elements "B", "A", "D", "E", "C", and "F" are added to the
hs.add("A"); HashSet.
hs.add("D"); 3.Printing the HashSet
hs.add("E"); •Unlike ArrayList or TreeSet, a HashSet does not maintain the
hs.add("C"); order of insertion.
hs.add("F"); •It internally uses a hashing mechanism to store elements
efficiently.
// Printing the HashSet
•When System.out.println(hs); is executed, the elements appear
System.out.println(hs);
} in random order, determined by the internal hash function.
}
Why is the Output Order Different?
Output: •HashSet does not guarantee any specific order.
[D, A, F, C, B, E] •The elements are stored based on their hash values, which can vary
in different executions.
•If you need a sorted order, use TreeSet instead of HashSet.
TreeSet
TreeSet extends AbstractSet and implements the NavigableSet interface.
It creates a collection that uses a tree for storage. Objects are stored in sorted,
ascending order. Access and retrieval times are quite fast, which makes TreeSet
an excellent choice when storing large amounts of sorted information that must
be found quickly. TreeSet is a generic class that has this declaration:
class TreeSet<E>
Here, E specifies the type of objects that the set will hold.
TreeSet has the following constructors:
TreeSet( )
TreeSet(Collection<? extends E> c)
TreeSet(Comparator<? super E> comp)
TreeSet(SortedSet<E> ss)
Example
import java.util.*;
class TreeSetDemo
{
public static void main(String args[])
{
TreeSet<String> ts = new TreeSet<String>();
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
The output from this program is shown here:
[A, B, C, D, E, F]
PriorityQueue
PriorityQueue extends AbstractQueue and implements the Queue interface.
It creates a queue that is prioritized based on the queue’s comparator.
PriorityQueue is a generic class that has this declaration:
class PriorityQueue<E>
Here, E specifies the type of objects stored in the queue. PriorityQueues are dynamic, growing as
necessary. PriorityQueue defines the six constructors shown here:
ArrayDeque
Java SE 6 added the ArrayDeque class, which extends AbstractCollection and implements the
Deque interface. It adds no methods of its own.
ArrayDeque creates a dynamic array and has no capacity restrictions.
ArrayDeque is a generic class that has this declaration:
class ArrayDeque<E>
Here, E specifies the type of objects stored in the collection.
ArrayDeque defines the following constructors:
ArrayDeque( )
ArrayDeque(int size)
ArrayDeque(Collection c)
Example:
import java.util.*;
class ArrayDequeDemo {
public static void main(String args[]) {
ArrayDeque<String> adq = new ArrayDeque<String>();
adq.push("A");
adq.push("B");
adq.push("D");
adq.push("E");
adq.push("F");
System.out.print("Popping the stack: ");
while(adq.peek() != null)
System.out.print(adq.pop() + " ");
System.out.println();
}
}
The output is shown here:
Popping the stack: F E D B A

peek() checks if the deque is not empty (returns the top element without removing it).
pop() removes and returns the top element.
This loop continues until the deque is empty.
Accessing a collection Via an Iterator:

Before you can access a collection through an iterator, you must obtain one. Each of the
collection classes provides an iterator( ) method that returns an iterator to the start of the collection.
By using this iterator object, you can access each element in the collection. Element at a time. In
general, to use an iterator to cycle through the contents of a collection,

1. Using an Iterator with a Collection:


The Iterator interface is part of java.util and is commonly used with collections like ArrayList,
HashSet, etc.
• Use Iterator when you need only forward traversal.
• Use ListIterator when you need both forward and backward traversal.
• Always use remove() from the Iterator itself to avoid ConcurrentModificationException.
Random Access Interface:

RandomAccess interface contains no members.


However, by implementing this interface, a collection signals that it supports
efficient random access to its elements.
By checking for the RandomAccess interface, client code can determine at run
time, whether a collection is suitable for certain types of random-access operations
—especially as they apply to large collections.
RandomAccess is implemented by ArrayList and by the legacy Vector class,
among others.

Note: Try yourself Write a java program to use Random Access Interface.
The Map Interfaces

The Map interface maps unique keys to values. A key is an object that you use to
retrieve a value at a later date. Given a key and a value, we can store the value in a
Map object. After the value is stored, you can retrieve it by using its key.
The map interfaces define the character and nature of maps.
Map is generic:
interface Map <K, V>

Here, K specifies the type of keys, and V specifies the type of values. The methods
declared by Map.
Working With Maps:
A map is an object that stores associations between keys and values, or
key/value pairs. Keys and values are objects. Keys must be unique, but the values
may be duplicated.
Some maps can accept a null key and null values, others cannot. There is one
key point about maps that is important to mention at the outset: they don’t
implement the Iterable interface. This means that you cannot cycle through a map
using a for-each style for loop. Furthermore, you can’t obtain an iterator to a map.
However, as you will soon see, you can obtain a collection-view of a map,
which does allow the use of either the for loop or an iterator.
A Map in Java is a collection that stores key-value pairs. Unlike List
and Set, a Map does not allow duplicate keys but can have duplicate
values.
Common implementations of Map in Java include(HLTH):
1. HashMap (unordered, fast)
2. LinkedHashMap (insertion order maintained)
3. TreeMap (sorted order)
4. Hashtable (synchronized, thread-safe)
HashMap:
The HashMap class extends AbstractMap and implements the Map interface. It uses a hash
table to store the map.
This allows the execution time of get( ) and put( ) to remain constant even for large sets.
HashMap is a generic class that has this declaration:
class HashMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
The following constructors are defined:
1. HashMap( )
2. HashMap(Map<? extends K, ? extends V> m)
3. HashMap(int capacity)
4. HashMap(int capacity, float fillRatio)
HashMap implements Map and extends AbstractMap. It does not add any methods of its own.
// Iterating through the Map
1. Creating and Using a HashMap System.out.println("HashMap contents:");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
Example: Basic Operations with HashMap System.out.println("Key: " + entry.getKey() + ", Value:
" + entry.getValue());
import java.util.*; }
}
class HashMapExample { }
public static void main(String[] args) {
// Creating a HashMap
HashMap<Integer, String> map = new HashMap<>();

// Adding key-value pairs


map.put(101, "Alice");
map.put(102, "Bob");
In Java, map.entrySet() is a method of the Map
map.put(103, "Charlie");
interface that returns a Set view of the mappings
// Accessing a value using key contained in the map. Each element in this set is a
System.out.println("Value for key 102: " + Map.Entry<K, V> object, where K is the key type
map.get(102)); and V is the value type
TreeMap :
The TreeMap class extends AbstractMap and implements the NavigableMap
interface. It creates maps stored in a tree structure.

A TreeMap provides an efficient means of storing key/value pairs in sorted


order and allows rapid retrieval. we should note that, unlike a hash map, a tree map
guarantees that its elements will be sorted in ascending key order.
TreeMap is a generic class that has this declaration:
class TreeMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
The following TreeMap constructors are defined:
1. TreeMap( )
2. TreeMap(Comparator comp)
3. TreeMap(Map m)
4. TreeMap(SortedMap sm)
• First form constructs an empty tree map that will be sorted by using the natural order of its
keys.
• Second form constructs an empty tree-based map that will be sorted by using the
Comparator comp. (Comparators are discussed later in this chapter.)
• Third form initializes a tree map with the entries from m, which will be sorted by using the
natural order of the keys.
• Fourth form initializes a tree map with the entries from sm, which will be sorted in the same
order as sm.

TreeMap has no methods beyond those specified by the NavigableMap interface and the
AbstractMap class.
LinkedHashMap
LinkedHashMap extends HashMap.
It maintains a linked list of the entries in the map, in the 1order in which they were inserted. This
allows insertion-order iteration over the map. That is, when iterating through a collection-view of a
LinkedHashMap, the elements will be returned in the order in which they were inserted.

LinkedHashMap that returns its elements in the order in which they were last accessed.
LinkedHashMap is a generic class that has this declaration:

class LinkedHashMap<K, V>


Here, K specifies the type of keys, and V specifies the type of values.

LinkedHashMap defines the following constructors:


1. LinkedHashMap( )
2. LinkedHashMap(Map m)
3. LinkedHashMap(int capacity)
4. LinkedHashMap(int capacity, float fillRatio) 5. LinkedHashMap(int capacity, float
fillRatio, boolean Order). The first form constructs a default LinkedHashMap.
Conclusion
•Use HashMap for fast performance (if order doesn’t matter).
•Use LinkedHashMap when order matters.
•Use TreeMap when sorting by key is required.
•Use Hashtable for thread-safe operations.
Comparator interface
Comparator is a generic interface that has this declaration:
interface Comparator<T>
Here, T specifies the type of objects being compared.
The Comparator interface defines two methods: compare( ) and equals( ). The
compare( ) method, shown here, compares two elements for order:
int compare(T obj1, T obj2)
obj1 and obj2 are the objects to be compared. This method returns zero if the
objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise,
a negative value is returned.
ClassCastException if the types of the objects are not compatible for
comparison. By overriding compare( ), you can alter the way that objects are
ordered.
For example, to sort in reverse order, you can create a comparator that reverses
the outcome of a comparison.
The equals( ) method, shown here, tests whether an object equals the invoking
comparator:
boolean equals(Object obj)

Here, obj is the object to be tested for equality. The method returns true if obj and
the invoking object are both Comparator objects and use the same ordering.
Otherwise, it returns false.
The Collection Algorithms:
Collections Framework defines several algorithms that can be applied to collections and
maps.
Algorithms are defined as static methods within the Collections class.
• static <T> Boolean addAll(Collection <? super T> c, T ... elements)
Inserts the elements specified by elements into the collection specified by c. Returns true if the
elements were added and false otherwise.
• static <T> Queue<T> asLifoQueue(Deque<T> c)
Returns a last-in, first-out view of c.
• static <T>int binarySearch(List<? extends T> list, T value, Comparator<? super T> c)
Searches for value in list ordered according to c. Returns the position of value in list, or a
negative value if value is not found.
• static <T> int binarySearch(List<? extends Comparable<? super T>> list,T value) Searches
for value in list. The list must be sorted. Returns the position of value in list, or a negative
value if value is not found.
• static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> t)
Returns a run-time type-safe view of a collection. An attempt to insert an incompatible element
will cause a ClassCastException.

• static <E> List<E> checkedList(List<E> c, Class<E> t)


Returns a run-time type-safe view of a List. An attempt to insert an incompatible element will
cause a ClassCastException.

• static <K, V> Map<K, V> checkedMap(Map<K, V> c, Class<K> keyT, Class<V> valueT)
Returns a run-time type-safe view of a Map. An attempt to insert an incompatible element will
cause a ClassCastException.

• static <E> List<E> checkedSet(Set<E> c, Class<E> t)


Returns a run-time type-safe view of a Set. An attempt to insert an incompatible element will
cause a ClassCastException.

• static int frequency(Collection c, Object obj) Counts the number of occurrences of obj in c
and returns the result.
• static int indexOfSubList(List<?> list, List<?> subList)
Searches list for the first occurrence of subList. Returns the index of the first match, or –1 if no
match is found.

• static int lastIndexOfSubList(List<?> list, List<?> subList)


Searches list for the last occurrence of subList. Returns the index of the last match, or –1 if no
match is found.
Why Generic Collections?
By using generics, programmers can implement generic algorithms that work on
collections of different types, can be customized, and are type safe and easier to
read.
As mentioned at the start of this chapter, the entire Collections Framework was
refitted for generics when JDK 5 was released. Furthermore, the Collections
Framework is arguably the single most important use of generics in the Java API.

The reason for this is that generics add type safety to the Collections
Framework. Before moving on, it is worth taking some time to examine in detail
the significance of this improvement.
The Legacy Classes and Interfaces
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.

1. boolean hasMoreElements()
//It returns true while there are still more elements to extract, and returns false when all the
elements have been enumerated.

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

• Vector() //This creates a default vector, which has an initial size of 10.
• Vector( int size ) //This creates a vector whose initial capacity is specified by size.
• Vector(int size, int incr) //This creates a vector whose initial capacity is specified by size
and whose increment is specified by incr. The increment specifies the number of elements
to allocate each time when a vector is resized for addition of objects.

• Vector(Collection c) //This creates a vector that contains the elements of collection c.


Hashtable
Hashtable was part of the original java.util and is a concrete implementation of a
Dictionary.
HashMap, Hashtable stores key/value pairs in a hash table. However, neither keys
nor values can be null. When using a Hashtable, we specify an object that is used
as a key, and the value that we want linked to that key. The key is then hashed, and
the resulting hash code is used as the index at which the value is stored within the
table. Hashtable was made generic by JDK 5.

It is declared like this: class Hashtable<K, V>


1. Hashtable( )
2. Hashtable(int size)
3. Hashtable(int size, float fillRatio)
4. Hashtable(Map<? extends K, ? extends V> m)
Properties
Properties is a subclass of Hashtable. It is used to maintain lists of values in
which the key is a String and the value is also a String.
The Properties class is used by many other Java classes.
For example, it is the type of object returned by System.getProperties( ) when
obtaining environmental values.
Although the Properties class, itself, is not generic, several of its methods are.
Properties defines the following instance variable:
Properties defaults;
This variable holds a default property list associated with a Properties object.
Properties defines these constructors:
Properties( )
Properties(Properties propDefault)
Stack class
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack only defines the default constructor, which creates an empty stack. With the
release of JDK 5, Stack was retrofitted for generics and is declared as shown here:

class Stack <E>

Here, E specifies the type of element stored in the stack. Stack includes all the
methods defined by Vector.
Dictionary
Dictionary is an abstract class that represents a key/value storage repository and
operates much like Map.
Given a key and value, we can store the value in a Dictionary object. Once the
value is stored, we can retrieve it by using its key. Thus, like a map, a dictionary
can be thought of as a list of key/value pairs.
Although not currently deprecated, Dictionary is classified as obsolete, because it is
fully superseded by Map. However, Dictionary is still in use and thus, is fully
discussed here.

class Dictionary<K, V>

Here, K specifies the type of keys, and V specifies the type of values.
Parting Thoughts on Collections
The Collections Framework gives you, the programmer, a powerful set of well-engineered
solutions to some of programming’s most common tasks. Consider using a collection the next
time that you need to store and retrieve information. Remember, collections need not be reserved
for only the “large jobs,” such as corporate databases, mailing lists, or inventory systems. They
are also effective when applied to smaller jobs.
For example, a TreeMap might make an excellent collection to hold the directory
structure of a set of files. A TreeSet could be quite useful for storing project-management
information.
The Java Collection Framework is a powerful tool that simplifies data manipulation, but
choosing the right collection and applying best practices can significantly impact application
performance. Understanding when and how to use each collection ensures efficient memory
usage, scalability, and maintainability of Java applications.
The End
Summary :
The Java Collection Framework (JCF)
provides a unified architecture for storing,
manipulating, and processing data efficiently. It
includes interfaces (List, Set, Queue, Map),
implementations (ArrayList, HashSet,
TreeMap), and algorithms (sorting, searching).
JCF improves performance, scalability, and
flexibility in Java applications by offering dynamic
and optimized data structures.

You might also like