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

Adv_Java_Module-01[1]

IMP

Uploaded by

tejasprasanna16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Adv_Java_Module-01[1]

IMP

Uploaded by

tejasprasanna16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

Module 1

Collections and framework


The Java Collections Framework
• A coupled set of classes and interfaces that
implement commonly reusable collection data
structures.
• Designed and developed primarily by Joshua
Bloch (currently Chief Java Architect at
Google).
What is a Collection?
• An object that groups multiple elements into a
single unit.
• Sometimes called a container.
• A unified architecture for representing and
manipulating collections.
• Includes:
– Interfaces: A hierarchy of ADTs.
– Implementations
– Algorithms: The methods that perform useful
computations, such as searching and sorting, on
objects that implement collection interfaces.
• These algorithms are polymorphic: that is, the same method
can be used on many different implementations of the
appropriate collection interface
Benefits
• Reduces programming effort: By providing useful data
structures and algorithms, the Collections Framework frees you
to concentrate on the important parts of your program rather
than on the low-level "plumbing" required to make it work.
• Increases program speed and quality: Provides high
performance, high-quality implementations of useful data
structures and algorithms.
• Allows interoperability among unrelated APIs: APIs can
interoperate seamlessly, even though they were written
independently.
• Reduces effort to learn and to use new APIs
• Reduces effort to design new APIs
• Fosters software reuse: New data structures that conform to
the standard collection interfaces are by nature reusable.
Where is the Java Collections Framework?

• Package java.util.
• In this lecture we will survey the interfaces,
abstract classes and classes for linear data
structures provided by the Java Collections
Framework.
• We will not cover all of the details (e.g., the
exceptions that may be thrown).
Collection interfaces
• The core collection interfaces encapsulate
different types of collections.
• They represent the abstract data types that
are part of the collections framework. They
are interfaces so they do not provide an
implementation!
Traversing Collections in Java
• There are two ways to traverse collections:
– using Iterators.
• 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 implements Iterator, the
elements of any collection class can be accessed
through the methods defined by Iterator.
– with the (enhanced) for-each construct
MAP
• In addition to collections, the framework
defines several map interfaces and classes.
• Maps store key/value pairs. Although maps
are part of the Collections Framework, they
are not “collections” in the strict use of the
term.
• You can, however, obtain a collection-view of a
map.
• java.util contains a wide array of functionality,
it is quite large. Here is a list of its classes:
• The interfaces defined by java.util are shown
next:
Collections Overview
• The Collections Framework was designed to meet several
goals
• First, the framework had to be high-performance. The
implementations for the fundamental collections (dynamic
arrays, linked lists, trees, and hash tables) are highly
efficient.
• 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.
• Finally, mechanisms were added that allow the integration
of standard arrays into the Collections Framework
• 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.
Iterators.
• 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 implements Iterator, the
elements of any collection class can be accessed
through the methods defined by Iterator.
MAP
• In addition to collections, the framework defines
several map interfaces and classes.
• Maps store key/value pairs. Although maps are
part of the Collections Framework, they are not
“collections” in the strict use of the term
Recent Changes to Collections
• Generics Fundamentally Change the Collections Framework
– Generics add the one feature that collections had been missing:
type safety
– All collections are now generic,and many of the methods that
operate on collections take generic type parameters.
• Autoboxing Facilitates the Use of Primitive Types
– a collection can store only references, not primitive values. In
the past, if you wanted to store a primitive value, such as an int,
in a collection, you had to manually box it into its typewrapper
– it needed to be manually unboxed (by using an explicit cast) into
its proper primitive type
– There is no need to manually perform these operations since
java do it automatically
• The For-Each Style for Loop
The Collection Interfaces
Collection Interface
Declaration:

interface Collection <E>


E – specifies the type of objects that the
collection will hold.
List Interface
Declaration:

interface List <E>


E – specifies the type of objects that the list will
hold.
Set Interface
Declaration:

interface Set <E>


E – specifies the type of objects that the set will
hold.
SortedSet Interface
Declaration:

interface SortedSet <E>


E – specifies the type of objects that the set will
hold.
NavigableSet Interface
Declaration:

interface NavigableSet <E>


E – specifies the type of objects that the set will
hold.
Queue Interface
Declaration:

interface Queue <E>


E – specifies the type of objects that the queue
will hold.
Deque Interface
Declaration:

interface Deque <E>


E – specifies the type of objects that the deque
will hold.
The Collection Classes
The ArrayList Class
• The ArrayList class extends AbstractList and implements the List interface.
• ArrayList supports dynamic arrays that can grow as needed
• 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 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.
Obtaining an Array from an ArrayList
• You can do this by calling toArray( ), which is defined by
Collection.
• Several reasons exist 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
• two versions of toArray( ),
Object[ ] toArray( ) // return object
<T> T[ ] toArray(T array[ ]) //returns an array of elements
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>
• LinkedList has the two constructors shown here:
LinkedList( )
LinkedList(Collection<? extends E> c)
• Because LinkedList implements the Deque interface, you have access to the
methods defined by Deque.
• E.g
addFirst( ) or offerFirst( )- to add elements to the start of a list
addLast( ) or offerLast( )-To add elements to the end of the list.
getFirst( ) or peekFirst( )-To obtain the first element.
getLast( ) or peekLast( )-To obtain the last element.
removeFirst( ) or pollFirst( )-To remove the first element, use.
removeLast( ) or pollLast( )-To remove the last element, use.
get( ) the index at which the element is stored.
set( ) the index and its new value. To assign a new value
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( ), remove( ),
and size( ) to remain constant even for large sets.
• The following constructors are defined:
HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
• The fourth form initializes both the capacity and the fill
ratio (also called load capacity) 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.
• 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.
Note : the elements are not stored in sorted order, and the precise
output may vary
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>
• 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.
• By substituting LinkedHashSet for HashSet in the preceding
program.
• The output will be
[B, A, D, E, C, F]
which is the order in which the elements were inserted.
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.
• TreeSet has the following constructors:
TreeSet( )
TreeSet(Collection<? extends E> c)
TreeSet(Comparator<? super E> comp)
TreeSet(SortedSet<E> ss)
• 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.
Note: TreeSet stores its elements in a tree, they are automatically arranged
in sorted order,
• TreeSet implements the NavigableSet
interface (which was added by Java SE 6),
• you can use the methods defined by
NavigableSet to retrieve elements of a
TreeSet
System.out.println(ts.subSet()("C", "F"));
The output from this statement is shown here:
[C, D, E]
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 six constructors shown here:
PriorityQueue( )
PriorityQueue(int capacity)
PriorityQueue(int capacity, Comparator<? super E> comp)
PriorityQueue(Collection<? extends E> c)
PriorityQueue(PriorityQueue<? extends E> c)
PriorityQueue(SortedSet<? extends E> c)
The ArrayDeque Class
• ArrayDeque class, which extends AbstractCollection and implements the
Deque interface. It adds no methods of its own.
• ArrayDeque creates a dynamic array
• 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 EnumSet Class
• EnumSet extends AbstractSet and implements Set. It is specifically
for use with keys 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 17-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
• Often, you will want to cycle through the elements in a
collection.
• For example, you might want to display each element. One
way to do this is to employ an iterator.
• Iterator enables you to cycle through a collection,
obtaining or removing elements(one-way traversal).
• 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>
Using an Iterator
• In general, 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( ).
The For-Each Alternative to Iterators
Storing User-Defined Classes in Collections
Working with Maps
• A map is an object that stores associations
between keys and values, or key/value pairs.
• Given a key, you can find its value. Both keys and
values are objects. The keys must be unique, but
the values may be duplicated. Some maps can
accept a null key and null values, others cannot.
• Imp Note: Map 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.
The Map Interfaces
The SortedMap Interface
• The SortedMap interface extends Map. It ensures that the
entries are maintained in ascending order based on the
keys. SortedMap is generic and is declared as shown here:
interface SortedMap<K, V>
• Here, K specifies the type of keys, and V specifies the type
of values.
The NavigableMap Interface
• The NavigableMap interface was added by Java SE 6. It extends
SortedMap and declares the behavior of a map that supports the
retrieval of entries based on the closest match to a given key or
keys. NavigableMap is a generic interface that has this declaration:
interface NavigableMap<K,V>
• Here, K -keys, and V -type of the values associated with the keys.
• In addition to the methods that it inherits from
SortedMap,NavigableMap adds those summarized in Table 17-12.
• Several methods throw a ClassCastException when an object is
incompatible with the keys in the map.
• A NullPointerException is thrown if an attempt is made to use a
null object and null keys are not allowed in the set.
• An llegalArgumentException is thrown if an invalid argument is
used.
The Map.Entry Interface
• The Map.Entry interface enables you to work
with a map entry.
• Recall that the entrySet( ) method declared by
the Map interface returns a Set containing the
map entries.Each of these set elements is a
Map.Entry object.
• Map.Entry is generic and is declared like this:
interface Map.Entry<K, V>
• Here, K specifies the type of keys, and V
specifies the type of values
The Map Classes

• Notice that AbstractMap is a superclass for all concrete map implementations.


• WeakHashMap implements a map that uses “weak keys,” which allows an
element in a map to be garbage-collected when its key is otherwise unused
The HashMap Class
• 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:


HashMap( )
HashMap(Map<? extends K, ? extends V> m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
• The first form constructs a default hash map.
• The second form initializes the hash map by using the elements of
m.
• The third form initializes the capacity of the hash map to capacity.
• The fourth form initializes both the capacity and fill ratio of the
hash map by using its arguments.
• The meaning of capacity and fill ratio is the same as for HashSet,
described earlier.
• The default capacity is 16. The default fill ratio is 0.75.
• HashMap implements Map and extends AbstractMap. It does
not add any methods of its own.
• hash map does not guarantee the order of its elements sameas
Hashset
• The following program illustrates HashMap. It maps names to
account balances. Notice how a set-view is obtained and used.
• The keys and values are displayed by calling
the getKey( ) and getValue( ) methods that
are defined by Map.Entry
The TreeMap Class
• 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.
• You 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:
TreeMap( )
TreeMap(Comparator<? super K> comp)
TreeMap(Map<? extends K, ? extends V> m)
TreeMap(SortedMap<K, ? extends V> sm)
Note : they are sorted by first name instead of last name
The LinkedHashMap Class
• LinkedHashMap extends HashMap.
• It maintains a linked list of the entries in the map, in the order in which
they were inserted. This allows insertion-order iteration over the map.
• You can also create a 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:
LinkedHashMap( )
LinkedHashMap(Map<? extends K, ? extends V> m)
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)
LinkedHashMap(int capacity, float fillRatio, boolean Order)
• The last form allows you to specify whether the elements will be stored in
the linked list by insertion order, or by order of last access. If Order is true,
then access order is used. If Order is false, then insertion order is used.
The IdentityHashMap Class
• IdentityHashMap extends AbstractMap and
implements the Map interface.
• It is similar to HashMap except that it uses reference
equality when comparing elements.
• IdentityHashMap is a generic class that has this
declaration:
class IdentityHashMap<K, V>
• Here, K specifies the type of key, and V specifies the
type of value.
• The API documentation explicitly states that
IdentityHashMap is not for general use.
The EnumMap Class
• EnumMap extends AbstractMap and implements Map. It is
specifically for use with keys of an enum type.
• It is a generic class that has this declaration:
class EnumMap<K extends Enum<K>, V>
• Here, K specifies the type of key, and V specifies the type of value.
• Notice that K must extend Enum<K>, which enforces the
requirement that the keys must be of an enum type.
• EnumMap defines the following constructors:
EnumMap(Class<K> kType)
EnumMap(Map<K, ? extends V> m)
EnumMap(EnumMap<K, ? extends V> em)
• The first constructor creates an empty EnumMap of type kType.
• The second creates an EnumMap map that contains the same
entries as m.
• The third creates an EnumMap initialized with the values in em.
• EnumMap defines no methods of its own.
Comparators
• Both TreeSet and TreeMap store elements in sorted order.
• If you want to order elements a different way, then specify a Comparator
when you construct the set or map.
• 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
• 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
Using a Comparator
• The following program is an updated version of the TreeMap program
• In the previous version, the accounts were sorted by name, but the
sorting began with the first name.
• The following program sorts the accounts by last name. To do so, it
uses a comparator that compares the last name of each account.
• This results in the map being sorted by last name
• Explanation :
• The comparator class TComp compares two strings that hold first and
last names.
• It does so by first comparing last names. To do this, it finds the index of
the last space in each string and then compares the substrings of each
element that begin at that point.
• In cases where last names are equivalent, the first names are then
compared. This yields a tree map that is sorted by last name, and
within last name by first name.
• You can see this because Ralph Smith comes before Tom Smith in the
output.
o/p

notice that the accounts are now sorted by last name


The Legacy Classes and Interfaces
• Before Java 1.2 version there is no Collection
framework in java, instead java consists of some classes
and interfaces to hold the objects those are called
Legacy Classes and Interface
Legacy Class :
– Dictionary
– HashTable
– Properties
– Stack
– Vector
• Legacy Interface :
Enumeration
• Dictionary :
Dictionary is a abstract class, which holds the data as
Key/value pair. It works as Map collection.
• HashTable :
• HashTable is a part of java.util package and it is a concrete class which extends the
Dictionary class.
• In Java 1.2 version on ward HashTable class implemented the Map interface and it
is as part of Collection Framework.
• HashTable is synchronized.
• Properties :
• Properties class will hold the set of properties in Key/value pair. Properties class
extends HashTable class . This class is thread-safe , multiple threads can share
single Properties object without making externally Synchronization.
• Stack :
• Stack represents the Last-In-First-Out(LIFO). Stack class extends the Vector class.
Vector :
• Vector class is a grow-able array and is similar to ArrayList class with two
difference.
• Vector is a Synchronized.
• Vector is used where programmer didn't have knowledge of what the size of the
Array is.It means you can ignore the size of the Vector, even still Vector will work
without any exceptions.
• Enumeration interface defines method to
enumerate(obtain one at a time) through collection of
objects.
• This interface is superseded(replaced) by Iterator interface.
• However, some legacy classes such
as Vector and Properties defines several method in
which Enumeration interface is used.
• It specifies the following two methods
– boolean hasMoreElements() //
– Object nextElement() //It returns the next object in the
enumeration
vector
• Vector is similar to ArrayList which represents a dynamic array.
• There are two differences between Vector and ArrayList.
– First, Vector is synchronized while ArrayList is not,
– Second, it contains many legacy methods that are not part of the Collections
Framework.
• It means that multiple threads can modify the Vector in parallel without risk
of data corruption. If you want to do this with an ArrayList, you need to use
the synchronized keyword
• 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.
• Vector is declared like this:
class Vector<E>
• Here, E specifies the type of element that will be stored.
• Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection<? extends E> c)
o/p :
10
20
30
40
50
60
Thank You

You might also like