0% found this document useful (0 votes)
15 views

Module 01

Uploaded by

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

Module 01

Uploaded by

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

Module 01

The Collections Framework


java.util Package:
• The java.util package also contains one of Java’s most powerful subsystems: the
Collections Framework .
• The Collections Framework is a sophisticated hierarchy of interfaces and classes that provide
state-of-the-art technology for managing groups of objects.
• java.util package contains:
java.util Package:
java.util Package:
Collections Overview

• The Java Collections Framework standardizes the way in which groups of


objects are handled by your programs.

• The Collections Framework was designed to meet several goals.


• First, the framework had to be high-performance.
• Second, the framework had to allow different types of collections to work in a similar
manner and with a high degree of interoperability.
• Third, extending and/or adapting a collection had to be easy.

• Collections Framework is built upon a set of standard interfaces.

• Several standard implementations (such as LinkedList, HashSet, and


TreeSet) of these interfaces are provided that you may use as-is.
Collections Overview

• Algorithms are another important part of the collection mechanism.


• Algorithms operate on collections and are defined as static methods within the Collections
class. Thus, they are available for all collections.
• Each collection class need not implement its own versions.
• The algorithms provide a standard means of manipulating collections.

• An iterator offers a general-purpose, standardized way of accessing the


elements within a collection, one at a time.
• Thus, an iterator provides a means of enumerating the contents of a collection.
• Because each collection provides an iterator, the elements of any collection class can be
accessed through the methods defined by Iterator.
The Collection Interfaces
• The Collections Framework defines several core interfaces.
• Collection interfaces is necessary because they determine the fundamental nature of the collection
classes.
• Interfaces that underpin collections are summarized in the following table:
The Collection Interfaces

• In addition to the collection interfaces, collections also use the Comparator,


RandomAccess, Iterator, ListIterator, and Spliterator interfaces.

• Comparator defines how two objects are compared.


• Iterator, ListIterator, and Spliterator enumerate the objects within a collection.
• By implementing RandomAccess, a list indicates that it supports efficient, random
access to its elements.
The Collection Interfaces

The Collection Interface:


• The Collection interface is the foundation upon which the Collections
Framework is built because it must be implemented by any class that defines a
collection.

• Collection is a generic interface that has this declaration:


interface Collection<E>

• Here, E specifies the type of objects that the collection will hold.
• Collection extends the Iterable interface. This means that all collections can be cycled
through by use of the foreach style for loop.

• Collection declares the core methods that all collections will have. These
methods are summarized in Table 20-1.
The Collection
Interfaces
The Collection Interfaces

• Several of these methods can throw an UnsupportedOperationException.


• A ClassCastException is generated when one object is incompatible with
another, such as when an attempt is made to add an incompatible object to a
collection.
• A NullPointerException is thrown if an attempt is made to store a null object
and null elements are not allowed in the collection.
• An IllegalArgumentException is thrown if an invalid argument is used.
• An IllegalStateException is thrown if an attempt is made to add an element to
a fixed-length collection that is full.
The Collection Interfaces

The List Interface:


• The List interface extends Collection and declares the behavior of a collection
that stores a sequence of elements.
• Elements can be inserted or accessed by their position in the list, using a
zero-based index.
• A list may contain duplicate elements.
• List is a generic interface that has this declaration:
interface List<E>
• Here, E specifies the type of objects that the list will hold.

• In addition to the methods defined by Collection, List defines some of its own,
which are summarized in Table 20-2.
The Collection Interfaces
• several of these methods will throw an UnsupportedOperationException if the list cannot be
modified,
• a ClassCastException is generated when one object is incompatible with another, such as when an
attempt is made to add an incompatible object to a list.
• Also, several methods will throw an IndexOutOfBoundsException if an invalid index is used.
• A NullPointerException is thrown if an attempt is made to store a null object and null elements are
not allowed in the list.
• An IllegalArgumentException is thrown if an invalid argument is used.

• List includes the of( ) factory method, which has a number of overloads.
• Each version returns an unmodifiable, value-based collection that is comprised of the arguments that
it is passed.
• The primary purpose of of( ) is to provide a convenient, efficient way to create a small List collection.
• There are 12 overloads of of( ).
• One takes no arguments and creates an empty list.
• It is shown here: static <E> List<E> of( )
The Collection Interfaces
The Collection Interfaces

The Set Interface


• The Set interface defines a set.
• It extends Collection and specifies the behavior of a collection that does not allow duplicate
elements. Therefore, the add( ) method returns false if an attempt is made to add duplicate
elements to a set.
• With two exceptions, it does not specify any additional methods of its own.
• Set is a generic interface that has this declaration:
interface Set<E>
• Here, E specifies the type of objects that the set will hold.
• Set includes the of( ) factory method, which has a number of overloads.
• Each version returns an unmodifiable, value-based collection that is comprised of the
arguments that it is passed.
• The primary purpose of of( ) is to provide a convenient, efficient way to create a small Set
collection.
• There are 12 overloads of of( ). One takes no arguments and creates an empty set.
The Collection Interfaces
The Collection Interfaces
The SortedSet Interface
• The SortedSet interface extends Set and declares the behavior of a set sorted in ascending
order.
• SortedSet is a generic interface that has this declaration:
interface SortedSet<E>
• Here, E specifies the type of objects that the set will hold.
The Collection Interfaces

The NavigableSet Interface


• The NavigableSet interface extends SortedSet
and declares the behavior of a collection that
supports the retrieval of elements based on the
closest match to a given value or values.
• NavigableSet is a generic interface that has this
declaration:
interface NavigableSet<E>
• Here, E specifies the type of objects that the set will
hold.
The Collection Interfaces

The Queue Interface


• The Queue interface extends Collection and
declares the behavior of a queue, which is often
a first-in, first-out list.
• However, there are types of queues in which the
ordering is based upon other criteria.
• Queue is a generic interface that has this
declaration:
interface Queue<E>
• Here, E specifies the type of objects that the queue will
hold.
The Collection Interfaces

Queue offers several points of interest.


• First, elements can only be removed from the head of the queue.
• Second, there are two methods that obtain and remove elements: poll( ) and remove( ).
• The difference between them is that poll( ) returns null if the queue is empty, but remove( ) throws an exception.
• Third, there are two methods, element( ) and peek( ), that obtain but don’t remove the element at the
head of the queue.
• They differ only in that element( ) throws an exception if the queue is empty, but peek( ) returns null.
• Finally, notice that offer( ) only attempts to add an element to a queue. Because some queues have a
fixed length and might be full, offer( ) can fail.
The Collection Interfaces

The Deque Interface


• The Deque interface extends Queue and
declares the behavior of a double-ended queue.
• Double-ended queues can function as standard,
first-in, first-out queues or as last-in, firstout
stacks.
• Deque is a generic interface that has this
declaration:
interface Deque<E>
• Here, E specifies the type of objects that the deque will
hold.
The Collection Interfaces
The Collection Classes
• Collection classes are the standard classes that implement Collection Interfaces.
The Collection Classes
The ArrayList Class

• The ArrayList class extends AbstractList and implements the List interface.
• ArrayList is a generic class that has this declaration:
class ArrayList<E>
• Here, E specifies the type of objects that the list will hold.

• ArrayList supports dynamic arrays that can grow as needed.


• In Java, standard arrays are of a fixed length.
• After arrays are created, they cannot grow or shrink, which means that you must know in
advance how many elements an array will hold.
The Collection Classes
The ArrayList Class

• But, sometimes, you may not know until run time precisely how large an array you
need.
• To handle this situation, the Collections Framework defines ArrayList.
• In essence, an ArrayList is a variable-length array of object references.
• That is, an ArrayList can dynamically increase or decrease in size.
• Array lists are created with an initial size.
• When this size is exceeded, the collection is automatically enlarged.
• When objects are removed, the array can be shrunk.
The Collection Classes
The ArrayList Class

• ArrayList has the constructors shown here:


ArrayList( )
ArrayList(Collection<? extends E> c )
ArrayList(int capacity )

• The first constructor builds an empty array list.


• The second constructor builds an array list that is initialized with the elements of
the collection c.
• The third constructor builds an array list that has the specified initial
capacity.
• The capacity is the size of the underlying array that is used to store the elements.
• The capacity grows automatically as elements are added to an array list.
• An array list is created for objects of type String,
and then several strings are added to it.
The Collection Classes
The ArrayList Class
• When working with ArrayList, you will sometimes want to obtain an actual array that contains the
contents of the list.
• You can do this by calling toArray( ), which is defined by Collection.
• Several reasons exist why you might want to convert a collection into an array, such as:
• To obtain faster processing times for certain operations
• To pass an array to a method that is not overloaded to accept a collection
• To integrate collection-based code with legacy code that does not understand collections

• there are three versions of toArray( ), which are shown here :


• object[ ] toArray( )
• <T> T[ ] toArray(T[ ] array )
• default <T> T[ ] toArray(IntFunction<T[ ]> arrayGen )

• The first returns an array of Object.


• The second and third forms return an array of elements that have the same type as T.
• Here, we will use the second form because of its convenience.
The Collection Classes
The LinkedList Class
• The LinkedList class extends AbstractSequentialList and implements the List,
Deque, and Queue interfaces.
• It provides a linked-list data structure.
• LinkedList is a generic class that has this declaration:
class LinkedList<E>
• Here, E specifies the type of objects that the list will hold.

• LinkedList has the two constructors shown here:


1. LinkedList( )
2. LinkedList(Collection<? extends E> c )
• The first constructor builds an empty linked list.
• The second constructor builds a linked list that is initialized with the elements of
the collection c.
The Collection Classes
The LinkedList Class
• Because LinkedList implements the Deque interface, you have access to the methods defined by Deque.
• To add elements to the start of a list, you can use addFirst( ) or offerFirst( ).
• To add elements to the end of the list, use addLast( ) or offerLast( ).
• To obtain the first element, you can use getFirst( ) or peekFirst( ).
• To obtain the last element, use getLast( ) or peekLast( ).
• To remove the first element, use removeFirst( ) or pollFirst( ).
• To remove the last element, use removeLast( ) or pollLast( ).

• Because LinkedList implements the List interface,


• calls to add(E) append items to the end of the list, as do calls to addLast( ).
• To insert items at a specific location, use the add(int,E) form of add( ), as illustrated by the call to add(1,
"A2") in the example.
• Notice how the third element in ll is changed by employing calls to get( ) and set( ).
• To obtain the current value of an element, pass get( ) the index at which the element is stored.
• To assign a new value to that index, pass set( ) the index and its new value.
The Collection Classes
The HashSet Class
• HashSet extends AbstractSet and implements the Set interface.
• It creates a collection that uses a hash table for storage.
• HashSet is a generic class that has this declaration:
class HashSet<E>
• Here, E specifies the type of objects that the set will hold.

• A hash table stores information by using a mechanism called hashing.


• In hashing, the informational content of a key is used to determine a unique
value, called its hash code .
• The hash code is then used as the index at which the data associated with the key is
stored.
• The transformation of the key into its hash code is performed automatically—you
never see the hash code itself.
• Also, your code can’t directly index the hash table.
• The advantage of hashing is that it allows the execution time of add( ), contains( ),
The Collection Classes
The HashSet Class
• The following constructors are defined:
• HashSet( )
• HashSet(Collection<? extends E> c)
• HashSet(int capacity )
• HashSet(int capacity , float fillRatio )

• The first form constructs a default hash set.


• The second form initializes the hash set by using the elements of c.
• The third form initializes the capacity of the hash set to capacity. (The default capacity is 16.)
• The fourth form initializes both the capacity and the fill ratio (also called load factor ) of
the hash set from its arguments.
• The fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is
resized upward.
• Specifically, when the number of elements is greater than the capacity of the hash set multiplied by
its fill ratio, the hash set is expanded.
• For constructors that do not take a fill ratio, 0.75 is used.
The Collection Classes
The HashSet Class
• It is important to note that HashSet does not guarantee the order of its elements, because the process of
hashing doesn’t usually lend itself to the creation of sorted sets.
• If you need sorted storage, then another collection, such as TreeSet, is a better choice.
The Collection Classes
The LinkedHashSet Class
• The LinkedHashSet class extends HashSet and adds no members of its own.
• It is a generic class that has this declaration:
class LinkedHashSet<E>
• Here, E specifies the type of objects that the set will hold.
• Its constructors parallel those in HashSet.

• LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were
inserted.
• This allows insertion-order iteration over the set.
• That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they
were inserted.

• To see the effect of LinkedHashSet, try substituting LinkedHashSet for HashSet in the preceding
program.

The output will be


• [Beta, Alpha, Eta, Gamma, Epsilon, Omega]
The Collection Classes
The TreeSet Class
• 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.
The Collection Classes
The TreeSet Class
• TreeSet has the following constructors:
• TreeSet( )
• TreeSet(Collection<? extends E> c)
• TreeSet(Comparator<? super E> comp)
• TreeSet(SortedSet<E> ss)

• The first form constructs an empty tree set that will be sorted in ascending order according to the
natural order of its elements.
• The second form builds a tree set that contains the elements of c.
• The third form constructs an empty tree set that will be sorted according to the comparator specified
by comp.
• The fourth form builds a tree set that contains the elements of ss.
The Collection Classes
The TreeSet Class
Because TreeSet implements the NavigableSet
interface, you can use the methods defined by
NavigableSet to retrieve elements of a TreeSet.
For example, assuming the preceding program, the
following statement uses subSet( ) to obtain a subset
of ts that contains the elements between C (inclusive)
and F (exclusive).
It then displays the resulting set.

System.out.println(ts.subSet("C", "F"));
The output from this statement is shown here:
[C, D, E]

TreeSet stores its elements in a tree, they are


automatically arranged in sorted order, as the output
confirms.
The Collection Classes
The PriorityQueue Class

• 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 seven constructors shown here:


o PriorityQueue( )
o PriorityQueue(int capacity)
o PriorityQueue(Comparator<? super E> comp)
o PriorityQueue(int capacity, Comparator<? super E> comp)
o PriorityQueue(Collection<? extends E> c)
o PriorityQueue(PriorityQueue<? extends E> c)
o PriorityQueue(SortedSet<? extends E> c)
The Collection Classes
The PriorityQueue Class

• The first constructor builds an empty queue. Its starting capacity is 11.
• The second constructor builds a queue that has the specified initial capacity.
• The third constructor specifies a comparator,
• The fourth builds a queue with the specified capacity and comparator.
• The last three constructors create queues that are initialized with the elements of the collection
passed in c.
• In all cases, the capacity grows automatically as elements are added.
The Collection Classes
The PriorityQueue Class

• If no comparator is specified when a PriorityQueue is constructed, then the default comparator for
the type of data stored in the queue is used.
• The default comparator will order the queue in ascending order.
• Thus, the head of the queue will be the smallest value.
• However, by providing a custom comparator, you can specify a different ordering scheme.
• For example, when storing items that include a time stamp, you could prioritize the queue such that
the oldest items are first in the queue.
• You can obtain a reference to the comparator used by a PriorityQueue by calling its comparator( )
method, shown here:
Comparator<? super E> comparator( )
• It returns the comparator.
• If natural ordering is used for the invoking queue, null is returned.
The Collection Classes
The ArrayDeque Class
• The ArrayDeque class 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<? extends E> c)
• The first constructor builds an empty deque. Its starting capacity is 16.
• The second constructor builds a deque that has the specified initial capacity.
• The third constructor creates a deque that is initialized with the elements of the collection passed in c.
• In all cases, the capacity grows as needed to handle the elements added to the deque.
The Collection Classes
The EnumSet Class
• EnumSet extends AbstractSet and implements Set.
• It is specifically for use with elements of an enum type.
• It is a generic class that has this declaration:
class EnumSet<E extends Enum<E>>
• Here, E specifies the elements.
• Notice that E must extend Enum<E>, which enforces the requirement that the elements must be of the specified enum
type.
• EnumSet defines no constructors.
• Instead, it uses the factory methods shown in Table 20-7 to create objects.
• All methods can throw NullPointerException.
• The copyOf( ) and range( ) methods can also throw IllegalArgumentException.
• Notice that the of( ) method is overloaded a number of times.
• This is in the interest of efficiency.
• Passing a known number of arguments can be faster than using a vararg parameter when the number of
arguments is small.
Accessing a Collection via an Iterator
• To cycle through the elements in a collection, for ex, you might want to display each element, use an
iterator, which is an object that implements either the Iterator or the ListIterator interface.
• Iterator enables you to cycle through a collection, obtaining or removing elements.
• ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of
elements.
• Iterator and ListIterator are generic interfaces which are declared as shown here:
• interface Iterator<E>
• interface ListIterator<E>
• Here, E specifies the type of objects being iterated.
Accessing a Collection via an Iterator
Accessing a Collection via an Iterator
Using an Iterator

• To use an iterator to cycle through the contents of a collection, follow these steps:

1. Obtain an iterator to the start of the collection by calling the collection’s iterator(
) method.

2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.

3. Within the loop, obtain each element by calling next( ).


Accessing a Collection via an Iterator
The For-Each Alternative to Iterators
• If you won’t be modifying the contents of a collection or obtaining elements in reverse order, then the for-each
version of the for loop is often a more convenient alternative to cycling through a collection than is using an
iterator.
Accessing a Collection via an Iterator
Spliterators
• JDK 8 added another type of iterator called a spliterator that is defined by the Spliterator
interface.
• A spliterator cycles through a sequence of elements, and in this regard, it is similar to the iterators.
However, the techniques required to use it differ.
• Furthermore, it offers substantially more functionality than does either Iterator or ListIterator.
• Perhaps the most important aspect of Spliterator is its ability to provide support for parallel iteration
of portions of the sequence.
• Thus, Spliterator supports parallel programming.
• However, you can use Spliterator even if you won’t be using parallel execution. One reason you
might want to do so is because it offers a streamlined approach that combines the hasNext
and next operations into one method.

• Spliterator is a generic interface that is declared like this:


interface Spliterator<T>
• Here, T is the type of elements being iterated.
Accessing a Collection via an Iterator
Storing User-Defined Classes in Collections
• For the sake of simplicity, the foregoing examples have stored built-in objects, such as String or Integer, in a
collection.
• Of course, collections are not limited to the storage of built-in objects.
• The power of collections is that they can store any type of object, including objects of classes that you create.
• For example, consider the following example that uses a LinkedList to store mailing addresses:

You might also like