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

Java Collections and Generics: - Prashant Kumar

Introductory presentation on Collections and generics.

Uploaded by

Prashant Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Java Collections and Generics: - Prashant Kumar

Introductory presentation on Collections and generics.

Uploaded by

Prashant Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 48

Java Collections and Generics

-Prashant kumar
Objective

“WHEN TO USE WHICH DATA


STRUCTURE ”???
Data Structures

1. A data structure is an arrangement of data


in a computer’s memory.
2. It includes list, stack, binary trees, hash
tables, etc.
3. Algorithms manipulate the data in these
structures in various ways such as searching
and sorting.
What is a Collections framework?

• A framework is an extensive set of interfaces,


abstract classes and concrete classes together
with support tools
• Framework is provided in java.util package &
comprises three parts:
1. Core interfaces
2. Set of implementations.
3. Utility methods
Need of a framework????

• Pre Java SDK1.2, Java provided a handful of data


structures:

– Hash Table
– Vector
– Stack

• These were good and easy to use, but they were


not organized into a more general framework.

• Lacked interoperability.
Features of Collection framework

• Reduces programming effort.

• Increases Program Speed and Quality

• Provides interoperability between


unrelated APIs.

• Faster software reuse.


The Collection Landscape
Methods of Collection

The interface supports basic operations


like adding and removing. When you try to
remove
an element, only a single instance of the
element in the collection is removed, if
present.

The Collection interface also supports


query operations:
* int size()
* boolean isEmpty()
* boolean contains(Object element)
* Iterator iterator()

With the Iterator interface


methods, you can traverse a collection
from start to finish and safely remove
elements from
the underlying Collection.
Methods of Collection (Contd.)
Group operations
Other operations the Collection interface
supports are tasks done on groups of
elements
or the entire collection at once:
* boolean containsAll(Collection collection)
* boolean addAll(Collection collection)
* void clear()
* void removeAll(Collection collection)
* void retainAll(Collection collection)

The clear() method removes all elements from


the current collection. The
removeAll() method is like clear() but only
removes a subset of elements. The
retainAll() method is similar to the removeAll()
method but does what might be
perceived as the opposite: it removes from the
current collection those elements not in the
other collection, an intersection.
Collection Relationships

• There are a number of different predefined classes


that implement the Collection<T> interface

– Programmer defined classes can implement it also

• A method written to manipulate a parameter of type


Collection<T> will work for all of these classes,
either singly or intermixed

• There are two main interfaces that extend the


Collection<T> interface: The Set<T> interface and
the List<T> interface
Collection Relationships (Cont’d)

• Classes that implement the Set<T> interface do not


allow an element in the class to occur more than
once

– The Set<T> interface has the same method


headings as the Collection<T> interface, but in
some cases the semantics (intended meanings)
are different

– Methods that are optional in the Collection<T>


interface are required in the Set<T> interface
Collection Relationships (Cont’d)
• Classes that implement the List<T> interface have their
elements ordered as on a list

– Elements are indexed starting with zero

– A class that implements the List<T> interface allows


elements to occur more than once

– The List<T> interface has more method headings than the


Collection<T> interface

– Some of the methods inherited from the Collection<T>


interface have different semantics in the List<T> interface

– The ArrayList<T> class implements the List<T> interface


Methods in the Set<T> Interface
Set Interface

The Set interface extends the Collection interface and, by definition,


forbids duplicates within the collection. All the original methods are
present and no new methods are introduced. The concrete Set
implementation classes rely on the equals() method of the object added
to check for equality.

HashSet and TreeSet classes

Hash Set Tree Set


Storage method: hash table red black tree
Space used: O(n) O(n)
Put speed: O(1) O(lg n)
Iteration order: Arbitrary Sorted

Rule of thumb: Use a Tree only if you need them sorted, otherwise
use a Hash
Set Usage Example

import java.util.*;
public class SetExample {
public static void main(String args[]) {
Set set = new HashSet();
set.add("Bernadine");
set.add("Elizabeth");
set.add("Gene");
set.add("Elizabeth");
set.add("Clara");
System.out.println(set);
Set sortedSet = new TreeSet(set);
System.out.println(sortedSet);
}
}

Output of the Program: -

[Gene, Clara, Bernadine, Elizabeth]


[Bernadine, Clara, Elizabeth, Gene]
Abstract Set Class

AbstractSet class

The AbstractSet class overrides the equals() and


hashCode() methods to ensure
two equal sets return the same hash code. Two sets
are equal if they are the same size and contain the
same elements. By definition, the hash code for a set
is the sum of the hash codes for the elements of the
set. Thus, no matter what the internal ordering of the
sets, two equal sets will report the same hash code.
List Interface
List Interface

• An interface that extends the Collections


interface.
• An ordered collection .
– Stores element by position
– Includes index based operation.
• Allows duplicate elements.
Concrete List Implementations

• There are two concrete implementations of the List interface


– LinkedList
– ArrayList
• Which is best to use depends on specific needs.

ArrayList and LinkedList classes

There are two general-purpose List implementations in the Collections


Framework:
ArrayList and LinkedList. Which of the two List implementations you
use depends on your specific needs. If you need to support random
access, without inserting or removing elements from any place other
than the end, then ArrayList offers the optimal collection.
If, however, you need to frequently add and remove elements from
the middle of the list and only access the list elements sequentially,
then LinkedList offers the better implementation.
Array List

• Stores element in a contiguous block of memory


and automatically expandable.

• The collection efficiently (O(1)) inserts and


deletes elements at the rear of the list.
• Operations at Intermediate positions have O(n)
efficiency.
Linked List

• Elements have a value and links that


identify adjacent elements in the
sequence.
• Inserting or deleting elements are O(1)
operations.
List Interface (Contd.)

AbstractList and AbstractSequentialList classes

There are two abstract List implementations classes: AbstractList and


AbstractSequentialList. Like the AbstractSet class, they override the
equals() and hashCode() methods to ensure two equal collections return
the same hash code. Two sets are equal if they are the same size and
contain the same elements in the same order.
The hashCode() implementation is specified in the List interface
definition and implemented here.
Besides the equals() and hashCode() implementations, AbstractList and
AbstractSequentialList provide partial implementations of the remaining
List methods. They make the creation of concrete list implementations
easier, for random-access and sequential-access data sources,
respectively. Which set of methods you need to define depends on the
behavior you wish to support. One thing you'll never need to provide
yourself is an implementation of the Iterator iterator() method.
Maps

• Maps are similar to collections but are actually


represented by an entirely different class
hierarchy.
• Maps store objects by key/value pairs.
• Keys may not be duplicated.
• Each key may map to only one value.
Maps (Contd.)

• Java provides several common class implementations:


– HashMap
• A hashtable implementation of a map.
• Good for quick searching where order doesn’t matter.
– TreeMap
• A tree implementation of a map.
• Good when natural ordering is required.

• Map is an interface; you can’t say new Map ( )


• It’s poor style to expose the implementation, so:
• Good: Map map = new HashMap ( );
Bad: HashMap map = new HashMap ( );
Methods in Map Interface

• If the map already contains a given


key, put(key, value) replaces the
value associated with that key
• This means Java has to do equality
testing on keys
• With a HashMap implementation,
you need to define equals and
hashCode for all your keys
• With a TreeMap implementation, you
need to define equals and implement
the Comparable interface for all your
keys
Methods in Map Interface(Contd.)

Each element is a map has a key and value. Each


key-value pair is saved in a java.util.Map.Entry
object. A set of these map entries can be obtained
by calling a map's entrySet() method. Iterating
over a map is done by iterating over this set.

• public interface Entry {


Object getKey( );
Object getValue( );
Object setValue(Object value);
}
• This is a small interface for working
with the Collection returned by
entrySet( )
• Can get elements only from the
Iterator, and they are only valid
during the iteration
Methods in Map Interface(Contd.)
Example: -
public static void main(String[] args) {

Map map = new HashMap();

map.put("1", “Kunal");
map.put("3", “Varun");
map.put(“2", “Suraj");

Map map2 = new TreeMap(map);

map2.put(“4", “Vikram");

Set set = map2.entrySet();

Iterator iterator = map2.entrySet().iterator();

while(iterator.hasNext()){

Map.Entry entry = (Map.Entry)iterator.next();

System.out.println("Map Entry"+entry.getKey());
}
}
HashMap and TreeMap classes

HashMap and TreeMap classes


•As with all the concrete implementations, which implementation you use depends
on your specific needs: -
•For inserting, deleting, and locating elements in a Map, the HashMap offers
the best alternative.
•If, however, you need to traverse the keys in a sorted order, then TreeMap is
your better alternative.

• Depending upon the size of your collection, it may be faster to add elements to a
HashMap, then convert the map to a TreeMap for sorted key traversal.
•Using a HashMap requires that the class of key added have a well-defined
hashCode() implementation.
•With the TreeMap implementation, elements added to the map must be sortable.
To optimize HashMap space usage, you can tune the initial capacity and load
factor.
•The TreeMap has no tuning options, as the tree is always balanced. Both
HashMap and TreeMap implement the Cloneable interface.
Performance Difference between
ConcurrentHashMap and synchronised HashMap

• Since the introduction of ConcurrentHashMap in Java 5 , it has been the


better choice over HashMap in highly threaded applications.
• For N threads concurrently execute a loop that chooses a random key and
looks up value corresponding to that key.
• If the value is found, it is removed with a probability of 0.02. If not, it is
added to the map with a probability of 0.6.

The result is ConcurrentHashMap performs much better when number of


threads increases
AbstractMap and WeakHashMap Classes
AbstractMap class
Similar to the other abstract collection implementations, the AbstractMap class
overrides the equals() and hashCode() methods to ensure two equal maps return
the same hash code.
WeakHashMap class
• A WeakHashMap is a special-purpose implementation of Map for storing only
weak references to the keys.
• This allows for the key-value pairs of the map to be garbage collected when the
key is no longer referenced outside of the WeakHashMap.
• Using WeakHashMap is beneficial for maintaining registry-like data structures,
where the usefulness of an entry vanishes when its key is no longer reachable by
any thread.
•The WeakHashMap functions identically to the HashMap with one very important
exception: if the Java memory manager no longer has a strong reference to the
object specified as a key, then the entry in the map will be removed.
Comparable and Comparator Interface
Comparable Comparator

• A Comparable object can compare • A Comparator object is used to


itself to another Object using its compare two objects of the same type
compareTo(Object other) method. The using the compare(Object other1,
object itself defines how the Object other2) method. When using a
comparison is done. Comparator, the objects being
compared don't need to define the rule
of comparison.

• Interface Comparable<T> has a • Interface Comparator<T> has a method:


method: public int compare(T o1, T o2)
public int compareTo(T o)

• Only one sort sequence can be • Many sort sequences can be created.
created.
Read-Only Collections
After you've added all the necessary elements to a collection, it may be convenient
to treat that collection as read-only, to prevent the accidental modification of the
collection.
To provide this capability, the Collections class provides six factory methods, one
for each of Collection, List, Map, Set, SortedMap, and SortedSet.

Collection unmodifiableCollection(Collection collection)


List unmodifiableList(List list)
Map unmodifiableMap(Map map)
Set unmodifiableSet(Set set)
SortedMap unmodifiableSortedMap(SortedMap map)
SortedSet unmodifiableSortedSet(SortedSet set)

Once you've filled the collection, the best way to make the collection read-only is to
replace the original reference with the read-only reference. If you don't replace the
original reference, then the collection is not read-only, as you can still use the
original reference to modify the collection. The following program demonstrates the
proper way to make a collection read-only. In addition, it shows what happens
when you try to modify a read-only collection.

When run and the last add() operation is attempted on the read-only set, an
UnsupportedOperationException is thrown.
Read-Only Collections (Contd.)
public static void main(String[] args) {

Set set2 = new HashSet();


set2.add("Kunal");
set2.add("Vinod");
set2.add("Prashant");

set2 = Collections.unmodifiableSet(set2);

set2.add("Sushant");
}

Exception Thrown

Exception in thread "main" java.lang.UnsupportedOperationException


at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
Thread-Safe Collections (Contd.)
Thread-Safe Collections
• The key difference between the historical collection classes and the new
implementations within the Collections Framework is the new classes are not
thread-safe.
• If, however, you are using a collection in a multi-threaded environment, where
multiple threads can modify the collection simultaneously, the modifications need to
be synchronized.
• The Collections class provides for the the ability to wrap existing collections into
synchronized ones with another set of six methods:

Collection synchronizedCollection(Collection collection)


List synchronizedList(List list)
Map synchronizedMap(Map map)
Set synchronizedSet(Set set)
SortedMap synchronizedSortedMap(SortedMap map)
SortedSet synchronizedSortedSet(SortedSet set)

Unlike when making a collection read-only, you synchronize the collection


immediately after creating it. You also must make sure you do not retain a
reference to the original collection, or else you can access the collection
unsynchronized.
Singleton and Multiple Copies Collections
Singleton Collections
The Collections class provides for the ability to create single element sets fairly
easily. Instead of having to create the Set and fill it in separate steps, you can do it
all at once. The resulting Set is immutable.
Set set = Collection.singleton("Hello"); The Java 2 SDK, Standard Edition, version
1.3 adds the ability to create singleton lists and maps, too:
List singletonList(Object element)
Map singletonMap(Object key, Object value)

Multiple Copy Collections


If you need an immutable list with multiple copies of the same element, the
nCopies(int n, Object element) method of the Collections class returns just such the
List:
List fullOfNullList = Collection.nCopies(10, null); By itself, that doesn't seem too
useful. However, you can then make the list modifiable by passing it along to
another list:
List anotherList = new ArrayList(fullOfNullList); This now creates 10 element
ArrayList, where each element is null. You can now modify each element at will, as
it becomes appropriate.
Difference between HashMap and HashTable
1. The key difference between the two is that access to the Hashtable is
synchronized on the table while access to the HashMap isn't. You can add it, but it
isn't there by default.
2. Another difference is that iterator in the HashMap is fail-safe while the
enumerator for the Hashtable isn't. If you change the map while iterating, you'll
know.
3. And, a third difference is that HashMap permits null values in it, while Hashtable
doesn't.
Java Generics
Introduction

• Prior to the JDK 5.0 release, when you created a Collection,


you could put any object in it.

List myList = new ArrayList(10);


myList.add(new Integer(10));
myList.add("Hello, World");

• Getting items out of the collection required you to use a casting


operation:

Integer myInt = (Integer)myList.iterator().next();


Introduction (Contd.)

• If you accidentally cast the wrong type, the program


would successfully compile, but an exception would be
thrown at runtime.
• Use instanceof to avoid a blind cast

Iterator listItor = myList.iterator();


Object myObject = listItor.next();
Integer myInt = null;
if (myObject instanceof Integer) {
myInt = (Integer)myObject;
}
Generics

• J2SE 5.0 provides compile-time type safety with the Java


Collections framework through generics
• Generics allows you to specify, at compile-time, the types
of objects you want to store in a Collection. Then when
you add and get items from the list, the list already
knows what types of objects are supposed to be
acted on.
• So you don't need to cast anything. The "<>" characters
are used to designate what type is to be stored. If the
wrong type of data is provided, a compile-time exception
is thrown.
Generics (Contd.)

Example:

// old way of looping through a List of String objects


// without generics and an enhanced for loop
import java.util.*;
public class Old {
public static void main(String args[]) {
List list = Arrays.asList(args);
Iterator itor = list.iterator();
while (itor.hasNext()) {
String element = (String)itor.next();
System.out.println(element + " / " + element.length());
}}}

If you compile and run the Old class and then run it with a string, like this:
java Old Hello
you get: Hello / 5
What Generics are not ?

• Generics are not templates


• Unlike C++, generic declarations are
– Typechecked at compile time
– Generics are compiled once and for all
• Generic source code not exposed to user
• No bloat

The type
The type checking
checking with
with Java
Java 1.5
1.5 Generics
Generics
changes the
changes the way
way one
one programs
programs
Java 1.0 vs Generics

class Stack { class Stack<A> {


void push(Object o) void push(A a) { ... }
{ ... } A pop() { ... }
Object pop() { ... } ...}
...}
String s = "Hello"; String s = "Hello";
Stack st = new Stack(); Stack<String> st =
... new Stack<String>();
st.push(s); st.push(s);
... ...
s = (String) st.pop(); s = st.pop();
How to use Generics?

List<Integer> xs = new LinkedList<Integer>();


xs.add(new Integer(0));
Integer x = xs.iterator.next();

Compare with

List xs = new LinkedList();


xs.add(new Integer(0));
Integer x = (Integer)xs.iterator.next();
Use of WildCards

public class Census {


public static void addRegistry(Map<String, ? extends Person>
registry) { ...}
}...
// Assuming Drivers are a subtype of Person
Map<String, Driver> allDrivers = ...;
Census.addRegistry(allDrivers);
Implementing WildCards

• Type erasure
– Compile-time type checking uses generics
– Compiler eliminates generics by erasing them
• Compile List<T> to List, T to Object, insert casts

• “Generics are not templates”


– Generic declarations are typechecked
– Generics are compiled once and for all
• No instantiation
• No “code bloat”
Any Queries ???

Copyright© YAMAHA MOTOR SOLUTIONS INDIA PVT.LTD.

You might also like