0% found this document useful (0 votes)
16 views114 pages

Collection Framework 1

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

Collection Framework 1

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

• Collections overview, Collection Interfaces, The

Collection classes- Array List, Linked List, Hash


Set, TreeSet, Priority Queue, Array Deque.
Accessing a Collection via an Iterator, Using an
Iterator, The For-Each alternative, Map Interfaces
and Classes, Comparators, Collection algorithms,
Arrays, The Legacy Classes and Interfaces-
Dictionary, Hash table ,Properties, Stack, Vector,
More Utility classes, String Tokenizer , Bit Set,
Date, Calendar, Random ,Formatter.
• one feature of Java that has been most
significantly affected by generics is the
Collections Framework.
• A collection is a group of objects.
• The Collections Framework defines several
classes, such as lists and maps, that manage
collections.
• The collection classes have always been able to
work with any type of object.
• The java.util package contains the Collections
Framework.
Collections Overview
• The Collection framework represents a unified
architecture for storing and manipulating a group
of objects. It has:
 Interfaces and its implementations, i.e.,
classes
 Algorithm
• Algorithms operate on collections and are
defined as static methods within the Collections
class. Algorithms are available for all collections.
Collections Overview
• The Collections Framework was designed to meet
several goals:
1. The framework had to be high-performance. The
implementations for the fundamental collections
(dynamic arrays, linked lists, trees, and hash tables)
are highly efficient.
2. The framework had to allow different types of
collections to work in a similar manner and with a
high degree of interoperability.
3. Extending and/or adapting a collection had to be
easy. Toward this end, the entire Collections
Framework is built upon a set of standard interfaces
• All collections are now generic, and many of the
methods that operate on collections take generic
type parameters. Simply put, the addition of
generics affected every part of the Collections
Framework.
• Autoboxing/unboxing facilitates the storing of
primitive types in collections. ( a collection can
store only references, not primitive values.)
• A collection can be cycled through by use of the
for each style for loop.
The Collection Interfaces

• Java Collection framework provides many


interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).
• The collection interfaces determine the
fundamental nature of the collection classes.
In addition to the collection interfaces, collections also
use the Comparator, RandomAccess, Iterator, and
ListIterator interfaces
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>
Collection declares the core methods that all
collections will have:
• 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.
• The Set interface defines a set. It extends
Collection and specifies the behavior of a
collection that does not allow duplicate elements.
• The Queue interface extends Collection and
declares the behavior of a queue, which is often
a first-in, first-out list. Declaration: interface
Queue<E>
• 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, first out
stacks.
Collection classes
collection classes
• The collection classes implement the collection
interfaces.
ArrayList Class
• standard arrays are of fixed length. Once they are
created, they cannot grow or shrink, i.e, how many
elements an array will hold must be known in advance.
• 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.
• ArrayList is a part of collection framework.
• It is present in java.util package.
• 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.
• 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
• ArrayList has the constructors shown here:
1. ArrayList( )
2. ArrayList(Collection c)
3. 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.
// Demonstrate ArrayList. al.add("F");
import java.util.*; al.add(1, "A2");
class ArrayListDemo { System.out.println("Size of al after
public static void main(String additions: " + al.size());
args[]) { // Display the array list.
// Create an array list. System.out.println("Contents of al:
ArrayList<String> al = new " + al);
ArrayList<String>(); // Remove elements from the array
System.out.println("Initial size of list.
al: " + al.size()); al.remove("F");
// Add elements to the array list. al.remove(2);
al.add("C"); System.out.println("Size of al after
al.add("A"); deletions: " +
al.add("E"); al.size());
al.add("B"); System.out.println("Contents of al:
al.add("D"); " + al);
}}
• The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
LinkedList Class
• The LinkedList class extends AbstractSequentialList and
implements the List, Deque, and Queue interfaces.
• 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 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.
• Few methods:
• to add elements to the start of a list: addFirst( )
or offerFirst( ).
• To add elements to the end of the list:addLast( )
or offerLast( ).
• To obtain the first element: getFirst( ) or
peekFirst( ).
• To obtain the last element:getLast( ) or peekLast()
• To remove the first element: removeFirst( ) or
pollFirst( ).
• To remove the last element: removeLast( ) or
pollLast( ).
// Demonstrate LinkedList. // Remove elements from the linked
import java.util.*; list.
class LinkedListDemo { ll.remove("F");
public static void main(String args[]) { ll.remove(2);
LinkedList<String> ll = new System.out.println("Contents of ll
LinkedList<String>(); after deletion: "
// Add elements to the linked list. + ll);
ll.add("F"); // Remove first and last elements.
ll.add("B"); ll.removeFirst();
ll.add("D"); ll.removeLast();
ll.add("E"); System.out.println("ll after deleting
ll.add("C"); first and last: "
ll.addLast("Z"); + ll);
ll.addFirst("A"); // Get and set a value.
ll.add(1, "A2"); String val = 11.get(2);
System.out.println("Original contents ll.set(2, val + " Changed");
of ll: " + ll); System.out.println("ll after change: "
+ ll);}}
• The output from this program is shown here:
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
Hash Set
• Hashset creates a collection that uses a hash
table for storage. hash table stores information by
using a mechanism called hashing.
• HashSet extends AbstractSet and implements the
Set interface.
• HashSet is a generic class that has this
declaration:
class HashSet<E>
Here, E specifies the type of objects that the set
will hold.
• The following constructors are defined :
1. HashSet( )
2. HashSet(Collection c)
3. HashSet(int capacity)
4. 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 capacity ) of the hash set from its arguments. The fill ratio
must be between 0.0 and 1.0,
• The fill ratio 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.
• // Demonstrate HashSet.
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet<String> hs = new HashSet<String>();
// Add elements to the hash set.
hs.add("Beta");
hs.add("Alpha");
hs.add("Eta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Omega");
System.out.println(hs);
}
}
The following is the output from this program:
[Gamma, Eta, Alpha, Epsilon, Omega, Beta]
The elements are not stored in sorted order, and the precise output may vary.
The TreeSet Class
• 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 extends AbstractSet and implements the NavigableSet
interface.
• 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:
1. TreeSet( )
2. TreeSet(Collection c)
3. TreeSet(Comparator comp)
4. TreeSet(SortedSet 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.
// Demonstrate TreeSet.
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);
System.out.println(ts.subSet("C", "F"));
}
}
The output from this program is shown here:
[A, B, C, D, E, F]
[C, D, E]
Priority Queue class
• Priority Queue: It creates a queue that is prioritized based on the queue’s
comparator.
• PriorityQueue extends AbstractQueue and implements the Queue
interface.
• 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:
1. PriorityQueue( )
2. PriorityQueue(int capacity)
3. PriorityQueue(Comparator comp) (Added by JDK 8.)
4. PriorityQueue(int capacity, Comparator comp)
5. PriorityQueue(Collection c)
6. PriorityQueue(PriorityQueue c)
7. PriorityQueue(SortedSet c)
• 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.
The ArrayDeque Class
• ArrayDeque is also known as Array Double Ended Queue or
Array Deck. This is a special kind of array that grows and
allows users to add or remove an element from both the
sides of the queue.
• The ArrayDeque class extends AbstractCollection and
implements the Deque interface.
• 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)
• 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.
// Demonstrate ArrayDeque.
import java.util.*;
class ArrayDequeDemo {
public static void main(String args[]) {
ArrayDeque<String> adq = new ArrayDeque<String>();
// Use an ArrayDeque like a stack.
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
Using an Iterator, The For-Each alternative
• Accessing a Collection i.e, to cycle through the elements in a
collection
1. via an Iterator
2. Using enhanced for loop

1. via an Iterator: iterator, 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>
Using an Iterator
• Before you can access a collection through an iterator,
you must obtain one iterator object.
• 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, one element at a time.
• 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.
// Demonstrate iterators. // Modify objects being iterated.
import java.util.*; ListIterator<String> litr = al.listIterator();
class IteratorDemo { while(litr.hasNext()) {
public static void main(String args[]) { String element = litr.next();
// Create an array list. litr.set(element + "+");
ArrayList<String> al = new }
ArrayList<String>(); System.out.print("Modified contents of al:
al.add("C"); ");
al.add("A"); itr = al.iterator();
al.add("E"); while(itr.hasNext()) {
al.add("B"); String element = itr.next();
al.add("D"); System.out.print(element + " ");
al.add("F"); }
// Use iterator to display contents of al. System.out.println();
System.out.print("Original contents of al: // Now, display the list backwards.
“ ); System.out.print("Modified list
Iterator<String> itr = al.iterator(); backwards: ");
while(itr.hasNext()) { while(litr.hasPrevious()) {
String element = itr.next(); String element = litr.previous();
System.out.print(element + " "); System.out.print(element + " ");
} }
System.out.println(); System.out.println();
}
}
• The output is shown here:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+

Note: 1.The program uses an ArrayList object, but the


general principles apply to any type of collection.
2. After the list is modified, litr points to the end of
the list.
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.
// Use the for-each for loop to for(int v : vals)
cycle through a collection. System.out.print(v + " ");
import java.util.*; System.out.println();
class ForEachDemo { // Now, sum the values by using a
public static void main(String for loop.
args[]) { int sum = 0;
// Create an array list for integers. for(int v : vals)
ArrayList<Integer> vals = new sum += v;
ArrayList<Integer>(); System.out.println("Sum of values:
// Add values to the array list. " + sum);
vals.add(1); }
vals.add(2); }
vals.add(3); The output from the program is
vals.add(4); shown here:
vals.add(5); Contents of vals: 1 2 3 4 5
// Use for loop to display the Sum of values: 15
values.
System.out.print("Contents of vals:
");
• the for loop is :
1. It is shorter and simpler to use than the iterator
based approach.
2. It can only be used to cycle through a collection in
the forward direction
3. It can’t be used to modify the contents of the
collection.
Maps
• Map interfaces, Map classes
• A map is an object that stores associations between
keys and values, or key/value pairs.
• maps are not, themselves, collections because they
do not implement the Collection interface.
• The keys must be unique, but the values may be
duplicated.
• Some maps can accept a null key and null values,
others cannot
• Maps don’t implement the Iterable interface. can’t
obtain an iterator to a map. This means that you
cannot cycle through a map
Interfaces related to maps

The Map Interface


• The Map Interface is generic and is declared as shown here:
interface Map<K, V>
Here, K specifies the type of keys, and V specifies the type of values
• 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, you can store the value in a
Map object. After the value is stored, you can retrieve it by using its key.
Few methods declared by Map:
• get( ): To obtain a value, use get( ), passing the key as an argument. The value is
returned.
• put( ): To put a value into a map, use put( ), specifying the key and the value.
• entrySet( ): used to obtain a collection-view of a map. It returns a Set that contains
the elements in the map.
• keySet( ): To obtain a collection-view of the keys.
SortedMap interface
• The SortedMap interface extends Map. It ensures that the
entries are maintained in ascending order based on the keys.
• Few methods of Sorted Map are : headMap( ), tailMap( ),
subMap, firstKey( ), lastKey( ).
NavigableMap Interface
• The NavigableMap interface 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.
The Map.Entry Interface
• This is the inner class of Map
• The Map.Entry interface enables you to work with a map
entry. Recall that the method declared by the Map interface
returns a Set containing the map entries.
• Each of the set elements returned by entrySet( ) is a
The Map Classes
• Several classes provide implementations of the map
interfaces. They are:
The HashMap Class
• It uses a hash table to store the map.
• The HashMap class extends AbstractMap and implements the Map
interface.
• 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 m)
3. HashMap(int capacity)
4. 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 default capacity is 16. The default fill ratio is 0.75.
• A hash map does not guarantee the order of its elements.
import java.util.*; for(Map.Entry<String, Double>
class HashMapDemo { me : set) {
public static void main(String System.out.print(me.getKey() + ":
args[]) { ");
// Create a hash map. System.out.println(me.getValue());
HashMap<String, Double> hm = }
new HashMap<String, Double>(); System.out.println();
// Put elements to the map // Deposit 1000 into John Doe's
hm.put("John Doe", new account.
Double(3434.34)); double balance = hm.get("John
hm.put("Tom Smith", new Doe");
Double(123.22)); hm.put("John Doe", balance +
hm.put("Jane Baker", new 1000);
Double(1378.00)); System.out.println("John Doe's
hm.put("Tod Hall", new new balance: " + hm.get("John
Double(99.22)); Doe"));
hm.put("Ralph Smith", new }
Double(-19.08)); }
// Get a set of the entries. Output from this program is shown
Set<Map.Entry<String, Double>> here (the precise order may vary):
set = hm.entrySet(); Ralph Smith: -19.08
The TreeMap Class
• TreeMap 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.
• The TreeMap class extends AbstractMap and
implements the NavigableMap interface.
• 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 following are the TreeMap constructors:
1. TreeMap( )
2. TreeMap(Comparator comp)
3. TreeMap(Map m)
4. TreeMap(SortedMap sm)
• The first form constructs an empty tree map that will be
sorted by using the natural order of its keys.
• The second form constructs an empty tree-based map
that will be sorted by using the Comparator comp.
• The third form initializes a tree map with the entries
from m, which will be sorted by using the natural order
of the keys.
• The fourth form initializes a tree map with the entries
public static void main(String set = tm.entrySet();
args[]) { // Display the elements.
// Create a tree map. for(Map.Entry<String, Double>
TreeMap<String, Double> tm = me : set) {
new TreeMap<String, Double>(); System.out.print(me.getKey() + ":
// Put elements to the map. ");
tm.put("John Doe", new System.out.println(me.getValue());}
Double(3434.34)); System.out.println();
tm.put("Tom Smith", new // Deposit 1000 into John Doe's
Double(123.22)); account.
tm.put("Jane Baker", new double balance = tm.get("John
Double(1378.00)); Doe");
tm.put("Tod Hall", new tm.put("John Doe", balance +
Double(99.22)); 1000);
tm.put("Ralph Smith", new System.out.println("John Doe's
Double(-19.08)); new balance: " +
tm.get("John Doe"));
}}
The following is the output from this program:
Jane Baker: 1378.0
John Doe: 3434.34
Ralph Smith: -19.08
Todd Hall: 99.22
Tom Smith: 123.22
John Doe's current balance: 4434.34
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. So, while iterating, the
elements will be returned in the order in which they
were inserted.
• This allows insertion-order iteration over the map.
• 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.
• The second form initializes the LinkedHashMap with the elements
from m.
• The third form initializes the capacity.
• The fourth form initializes both capacity and fill ratio. The
meaning of capacity and fill ratio are the same as for HashMap.
The default capacity is 16. The default ratio is 0.75.
• 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,
The IdentityHashMap Class
• It is similar to HashMap except that it uses reference
equality when comparing elements. IdentityHashMap
extends AbstractMap and implements the Map
interface.
The EnumMap Class
• It is specifically for use with keys of an enum type.
• EnumMap extends AbstractMap and implements Map.
• 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 is specialized implementation of Map
interface for enumeration types.
• EnumMap is an ordered collection and they are
maintained in the natural order of their keys(here
order means the order on which enum constant are
declared inside enum type )
• It’s a high performance map implementation, much
faster than HashMap.
• EnumMap doesn’t allow null key and throw
NullPointerException, at same time null values are
permitted.
Comparators
• By default, TreeSet ,TreeMap classes store their
elements by using what Java refers to as “natural
ordering”.
• If the elements are to be ordered in 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.
• Few methods:
• compare( ): compares two elements for order
int compare(T obj1, T obj2)
• Zero: objects are equal.
• Positive: if obj1 is greater than obj2.
• negative: if obj1 is lesser than obj2.

• equals( ): tests whether an object equals the invoking comparator


• boolean equals(object obj)
obj is the object to be tested for equality.
true: if obj and the invoking object are both Comparator objects and
use the same ordering. Otherwise, it returns false.
• reverseOrder( )
• naturalOrder( )
• nullsFirst( )
• nullsLast( ),
// Use a custom comparator. ts.add("C");
import java.util.*; ts.add("A");
// A reverse comparator for strings. ts.add("B");
class MyComp implements ts.add("E");
Comparator<String> { ts.add("F");
public int compare(String aStr, String bStr) { ts.add("D");
// Reverse the comparison.
return bStr.compareTo(aStr); // Display the elements.
} for(String element : ts)
// No need to override equals or the default System.out.print(element + " ");
methods. System.out.println();
} }
class CompDemo { }
public static void main(String args[]) { As the following output shows, the tree is now
// Create a tree set. sorted in reverse order:
TreeSet<String> ts = new TreeSet<String>(new FEDCBA
MyComp());
// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
• beginning with JDK 8, there is another way to approach a solution.
• It is now possible to simply call reversed( ) on a natural-order
comparator. It will return an equivalent comparator, except that it
runs in reverse.

class MyComp implements Comparator<String> {


public int compare(String aStr, String bStr) {
return aStr.compareTo(bStr);
}
}

MyComp mc = new MyComp(); // Create a comparator


// Pass a reverse order version of MyComp to TreeSet.
TreeSet<String> ts = new TreeSet<String>(mc.reversed());
Arrays
• The Arrays class provides various methods that are useful when working
with arrays. These methods help bridge the gap between collections and
arrays.
1. The asList( ) method: returns a List that is backed by a specified array.
– static <T> List asList(T... array)
Here, array is the array that contains the data.
2. binarySearch( ) method uses a binary search to find a specified value. This
method must be applied to sorted arrays.
Ex: static int binarySearch(int array[ ], int value)
Here, array is the array to be searched, and value is the value to be located.
3. The sort( ) method sorts an array so that it is arranged in ascending order.
4. The fill( ) method assigns a value to all elements in an array. In other words,
it fills an array with a specified value.
5 The equals( ) method returns true if two arrays are equivalent. Otherwise, it
returns false.
// Demonstrate Arrays // Sort and display the array.
import java.util.*; Arrays.sort(array);
class ArraysDemo {
public static void main(String args[]) { System.out.print("After sorting again: ");
// Allocate and initialize array. display(array);
int array[] = new int[10]; // Binary search for -9.
for(int i = 0; i < 10; i++) System.out.print("The value -9 is at
array[i] = -3 * i; location ");
// Display, sort, and display the array. int index =
System.out.print("Original contents: "); Arrays.binarySearch(array, -9);
display(array); System.out.println(index);
Arrays.sort(array); }
System.out.print("Sorted: "); static void display(int array[]) {
display(array); for(int i: array)
// Fill and display the array. System.out.print(i + " ");
Arrays.fill(array, 2, 6, -1); System.out.println();
System.out.print("After fill(): "); }
display(array); }
The following is the output from this program:
Original contents: 0 -3 -6 -9 -12 -15 -18 -21 -24 -27
Sorted: -27 -24 -21 -18 -15 -12 -9 -6 -3 0
After fill(): -27 -24 -1 -1 -1 -1 -9 -6 -3 0
After sorting again: -27 -24 -9 -6 -3 -1 -1 -1 -1 0
The value -9 is at location 2
The Collection Algorithms
• The Collections Framework defines several algorithms that can be
applied to collections and maps.
• These algorithms are defined as static methods within the Collections
class.
• Several of the methods can throw a ClassCastException, which occurs
when an attempt is made to compare incompatible types, or
an UnsupportedOperationException, which occurs when an attempt
is made to modify an unmodifiable collection.
// Demonstrate various algorithms. System.out.print("List sorted in reverse: ");
import java.util.*; for(int i : ll)
class AlgorithmsDemo { System.out.print(i+ " ");
public static void main(String args[]) { System.out.println();
// Create and initialize linked list. // Shuffle list.
LinkedList<Integer> ll = new Collections.shuffle(ll);
LinkedList<Integer>(); // Display randomized list.
ll.add(-8); System.out.print("List shuffled: ");
ll.add(20); for(int i : ll)
ll.add(-20); System.out.print(i + " ");
ll.add(8); System.out.println();
// Create a reverse order comparator. System.out.println("Minimum: " +
Comparator<Integer> r = Collections.min(ll));
Collections.reverseOrder(); System.out.println("Maximum: " +
// Sort list by using the comparator. Collections.max(ll));
Collections.sort(ll, r); Output from this program is shown here:
List sorted in reverse: 20 8 -8 -20
List shuffled: 20 -20 8 -8
Minimum: -20
Maximum: 20
Special utility classes
• Java.util also include some other classes which are not part of
the Collections Framework. StringTokenizer, Date,
RandomNumber, Formatter, Scanner etc.
StringTokenizer
• Divides text into a set of discrete parts, or tokens.
• The given input string is divided based on the delimiters
specified.
• Delimiters are characters that separate tokens. Each character
in the delimiters string is considered a valid delimiter.
• The StringTokenizer constructors are shown here:
1. StringTokenizer(String str)
2. StringTokenizer(String str, String delimiters)
3. StringTokenizer(String str, String delimiters, boolean
delimAsToken)
• The default set of delimiters consists of the whitespace
characters: space, tab, form feed, newline, and carriage
return.
• If delimeter set is “=“ : Sets the delimeter to =
• If delimeter set is “=“ ",;:" Sets the delimiters to a
comma, semicolon, and colon.
• In all versions, str is the string that will be tokenized. In
the first version, the default delimiters are used. In the
second and third versions, delimiters is a string that
specifies the delimiters.
• In the third version, if delimAsToken is true, then the
delimiters are also returned as tokens when the string is
parsed. Otherwise, the delimiters are not returned.
Delimiters are not returned as tokens by the first two
// Demonstrate StringTokenizer. String key = st2.nextToken();
import java.util.StringTokenizer; System.out.println(key);
class STDemo { }}}
static String in1 = "title Java The
Complete Reference author Schildt Output:
publisher McGraw- Title
Hill=copyright=2014 "; Java
The
static String in2 = "title-Java-The- Complete
Complete-Reference-author-Schildt- Reference
publisher-McGraw- Author
Hill=copyright=2014 "; Schildt
public static void main(String args[]) { Publisher
StringTokenizer st1 = new McGraw-Hill=copyright=2014
StringTokenizer(in1, " "); Title
while(st1.hasMoreTokens()) { Java
String key = st1.nextToken(); The
System.out.println(key); Complete
} Reference
StringTokenizer st2 = new Author
StringTokenizer(in2, "-"); Schildt
while(st2.hasMoreTokens()) { Publisher
McGraw-Hill=copyright=2014
BitSet
• A BitSet class creates a special type of array that
holds bit values in the form of boolean values. This
array can increase in size as needed. This makes it
similar to a vector of bits.
• The BitSet constructors are shown here:
1. BitSet( )
2. BitSet(int size)
• The first version creates a default object. The
second version allows you to specify its initial size
(that is, the number of bits that it can hold). All bits
are initialized to false.
• Few methods defined are:
• void set(int index): Sets the bit specified by index.
• void set(int index, boolean v): Sets the bit specified by
index to the value passed in v. true sets the bit; false
clears the bit.
• int size( ): Returns the number of bits in the invoking
BitSet object.
• int cardinality( ) :Returns the number of set bits in the
invoking object.
• void or(BitSet bitSet),
• boolean get(int index),
• boolean equals(Object bitSet),
• void clear( ) ,
// BitSet Demonstration.
import java.util.BitSet; // XOR bits
class BitSetDemo { bits2.xor(bits1);
public static void main(String args[]) { System.out.println("\nbits2 XOR bits1: ");
BitSet bits1 = new BitSet(16); System.out.println(bits2);
BitSet bits2 = new BitSet(16); }}
// set some bits
for(int i=0; i<16; i++) { The output from this program is shown
if((i%2) == 0) bits1.set(i); here. When toString( ) converts a BitSet
if((i%5) != 0) bits2.set(i); object to its
} string equivalent, each set bit is
System.out.println("Initial pattern in bits1: represented by its bit position. Cleared
"); bits are not shown.
System.out.println(bits1); Initial pattern in bits1:
System.out.println("\nInitial pattern in {0, 2, 4, 6, 8, 10, 12, 14}
bits2: "); Initial pattern in bits2:
System.out.println(bits2); {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
// AND bits bits2 AND bits1:
bits2.and(bits1); {2, 4, 6, 8, 12, 14}
System.out.println("\nbits2 AND bits1: "); bits2 OR bits1:
System.out.println(bits2); {0, 2, 4, 6, 8, 10, 12, 14}
// OR bits bits2 XOR bits1:
bits2.or(bits1); {}
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
Date
• The Date class encapsulates the current date and time.
• When Java 1.1 was released, many of the functions
carried out by the original Date class were moved into
the Calendar and DateFormat classes.
• Date supports the following non-deprecated
constructors:
1. Date( )
2. Date(long millisec)
• The first constructor initializes the object with the
current date and time.
• The second constructor accepts one argument that
equals the number of milliseconds that have elapsed
• Few methods:
• boolean after(Date date): Returns true if the invoking
Date object contains a date that is later than the one
specified by date. Otherwise, it returns false.
• boolean before(Date date): Returns true if the
invoking Date object contains a date that is earlier
than the one specified by date. Otherwise, it eturns
false.
• long getTime( ) Returns the number of milliseconds
that have elapsed since January 1, 1970.
• void setTime(long time)
• boolean equals(Object date)
• int compareTo(Date date)
// Show date and time using only Date methods.
import java.util.Date;
class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date);
// Display number of milliseconds since midnight, January 1, 1970 GMT
long msec = date.getTime();
System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);
}
}
Output:
Wed Oct 30 11:11:44 IST 2019
Calendar
• The abstract Calendar class provides a set of methods that allows
you to convert a time in milliseconds to a number of useful
components. Some examples of the type of information that can
be provided are year, month, day, hour, minute, and second.
• Calendar provides no public constructors.
• Calendar defines several protected instance Variables:
1. areFieldsSet: Is a boolean that indicates if the time components
have been set.
2. Fields: is an array of ints that holds the components of the time.
3. isSet : Is a boolean array that indicates if a specific time
component has been set.
4. time: Is a long that holds the current time for this object.
5. isTimeSet: Is a boolean that indicates if the current time has
been set.
class CalendarDemo { // Set the time and date information and
public static void main(String args[]) { display it.
String months[] = { calendar.set(Calendar.HOUR, 10);
"Jan", "Feb", "Mar", "Apr", calendar.set(Calendar.MINUTE, 29);
"May", "Jun", "Jul", "Aug", calendar.set(Calendar.SECOND, 22);
"Sep", "Oct", "Nov", "Dec"}; System.out.print("Updated time: ");
// Create a calendar initialized with the System.out.print(calendar.get(Calendar.HOUR)
// current date and time in the default + ":");
// locale and timezone. System.out.print(calendar.get(Calendar.MINU
Calendar calendar = Calendar.getInstance(); TE) + ":");
// Display current time and date information. System.out.println(calendar.get(Calendar.SEC
System.out.print("Date: "); OND));
System.out.print(months[calendar.get(Calendar. }
MONTH)]); }
System.out.print(" " + Date: Oct 28 2019
calendar.get(Calendar.DATE) + " "); Time: 8:41:17
System.out.println(calendar.get(Calendar.YEAR)) Updated time: 10:29:22
;
System.out.print("Time: ");
System.out.print(calendar.get(Calendar.HOUR)
+ ":");
System.out.print(calendar.get(Calendar.MINUTE
) + ":");
System.out.println(calendar.get(Calendar.SECO
ND));
Random
• The Random class is a generator of pseudorandom numbers.
they are simply uniformly distributed sequences.
• An instance of java Random class is used to generate random
numbers.
• This class provides several methods to generate random
numbers of type integer, double, long, float etc.
• Random number generation algorithm works on the seed
value. A random seed (or seed state, or just seed) is a number
used to initialize a pseudorandom number generator. i.e,
A random seed is a starting point in
generating random numbers. A random seed specifies the
start point when a computer generates a random number
sequence . If not provided, seed value is created from system
nano time.
• If two Random instances have same seed value, then they will
• Random defines the following constructors:
1. Random( )
2. Random(long seed)
• The first version creates a number generator that
uses a reasonably unique seed.
• The second form allows you to specify a seed value
manually.
import java.util.Random;
public class RandomNumberExample {
public static void main(String[] args) {
Random random = new Random();
System.out.println(random.nextBoolean());
System.out.println(random.nextDouble());
System.out.println(random.nextFloat());
System.out.println(random.nextInt());
//generates int value within specific limit
System.out.println(random.nextInt(20));
Random random1 = new Random(100);
Random random2 = new Random(100);
System.out.println(random1.nextInt());
System.out.println(random2.nextInt());
}}
Sample output:
true
0.6004484834191632
0.9999109
-483498368
17
-1193959466
-1193959466
Formatter class
• It is used for creating formatted output.
• Format conversions allows to display numbers, strings, time
and date in virtually any desired format .
• It operates in a manner similar to the C/C++ printf( )
function.
• The Formatter class defines many constructors:
1. Formatter( )
2. Formatter(Appendable buf)
3. Formatter(Appendable buf, Locale loc)
4. Formatter(String filename) throws FileNotFoundException
5. Formatter(String filename, String charset) throws
FileNotFoundException, UnsupportedEncodingException
6. Formatter(File outF) throws FileNotFoundException
• Before you can use Formatter to format output, you must
create a Formatter object.
• In general, Formatter works by converting the binary form
of data used by a program into formatted text. It stores the
formatted text in a buffer, the contents of which can be
obtained by the program whenever they are needed.
• buf : specifies a buffer for the formatted output
• The loc parameter specifies a locale.
• The filename parameter specifies the name of a file that
will receive the formatted output.
• The charset parameter specifies the character set.
• The outF parameter specifies a reference to an open file
that will receive output.
• The outStrm parameter specifies a reference to an output
• The format specifiers used are :%a %A Floating-point
hexadecimal
• %b%B Boolean
• %c Character
• %d Decimal integer
• %h %H Hash code of the argument
• %e %E Scientific notation
• %f Decimal floating-point
• %o Octal integer
• %n Inserts a newline character
• %s %S String
• %t %T Time and date
• %x %X Integer hexadecimal
/ A very simple example that uses Formatter.
import java.util.*;
class FormatDemo {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt.format("Formatting %s is easy %d %f", "with Java", 10, 98.6);
System.out.println(fmt);
fmt.close();
Formatter fmt1 = new Formatter();
Calendar cal = Calendar.getInstance();
// Display standard 12-hour time format.
fmt1.format("%tr", cal);
System.out.println(fmt1);
fmt1.close();
// Display complete time and date information.
Formatter fmt2 = new Formatter();
fmt2 = new Formatter();
fmt2.format("%tc", cal);
System.out.println(fmt2);
fmt2.close();
}}
Output:
Formatting with Java is easy 10 98.600000
07:46:30 PM
Tue Oct 29 19:46:30 IST 2019
• A more convenient alternative to formatter is the
printf( ) method. The printf( ) method automatically
uses Formatter to create a formatted string. It then
displays that string on System.out, which is the
console by default. The printf( ) method is defined
by both PrintStream and PrintWriter.
The Legacy Classes and Interfaces
• Early versions of java.util did not include the
Collections Framework. Instead, it defined several
classes and an interface that provided an ad hoc
method of storing objects.
• When collections were added (by J2SE 1.2), several
of the original classes were reengineered to support
the collection interfaces.
• Thus, they are now technically part of the
Collections Framework.
• However, where a modern collection duplicates the
functionality of a legacy class, you will usually want
to use the newer collection class.
Legacy Classes and Interfaces
• The legacy classes defined by java.util :
1. Dictionary
2. Hashtable
3. Properties
4. Stack
5. Vector
• legacy interface
1. Enumeration.
The Enumeration interface
• This legacy interface has been superseded by
Iterator.
• Used to obtain the elements in a collection of
objects one at a time.
• The declaration is:
• interface Enumeration<E>
where E specifies the type of element being
enumerated.
• Enumeration specifies the following two methods:
1. boolean hasMoreElements( )
2. E nextElement( )
Vector
• Vector implements a dynamic array.
• It is similar to ArrayList.
• Vector is synchronized, and it contains many legacy
methods that duplicate the functionality of methods defined
by the Collections Framework.
• Vector is declared like this:
class Vector<E>
Here, E specifies the type of element that will be
stored.
• Vector constructors:
1. Vector( )
2. Vector(int size)
3. Vector(int size, int incr)
• The first form creates a default vector, which has an initial size of 10.
• The second form creates a vector whose initial capacity is specified by
size.
• The third form 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 that a vector is resized
upward.
• The fourth form creates a vector that contains the elements of
collection c.

• Vector defines the following protected data members:


1. int capacityIncrement;
2. int elementCount;
3. Object[ ] elementData;
• The increment value is stored in capacityIncrement.
• The number of elements currently in the vector is stored in
elementCount.
• Methods:
// Demonstrate various Vector operations. v.addElement(11);
import java.util.*; v.addElement(12);
class VectorDemo { System.out.println("First element: " +
public static void main(String args[]) { v.firstElement());
// initial size is 3, increment is 2 System.out.println("Last element: " +
Vector<Integer> v = new Vector<Integer>(3, 2); v.lastElement());
System.out.println("Initial size: " + v.size()); if(v.contains(3))
System.out.println("Initial capacity: " + System.out.println("Vector contains 3.");
v.capacity()); // Enumerate the elements in the vector.
v.addElement(1); Enumeration<Integer> vEnum = v.elements();
v.addElement(2); System.out.println("\nElements in vector:");
v.addElement(3); while(vEnum.hasMoreElements())
v.addElement(4); System.out.print(vEnum.nextElement() + " ");
System.out.println("Capacity after four System.out.println();
additions: " + }
v.capacity()); }
v.addElement(5); The output from this program is shown here:
System.out.println("Current capacity: " + Initial size: 0
v.capacity()); Initial capacity: 3
v.addElement(6); Capacity after four additions: 5
v.addElement(7); Current capacity: 5
System.out.println("Current capacity: " + Current capacity: 7
v.capacity()); Current capacity: 9
v.addElement(9); First element: 1
v.addElement(10); Last element: 12
System.out.println("Current capacity: " + Vector contains 3.
v.capacity()); Elements in vector:
1 2 3 4 5 6 7 9 10 11 12
Stack
• 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.
• Declaration:
class Stack<E>
Here, E specifies the type of element stored in the
stack.
• Stack includes all the methods defined by Vector
and adds several of its own:
// Demonstrate the Stack class. try {
import java.util.*; showpop(st);
class StackDemo { } catch (EmptyStackException e) {
static void showpush(Stack<Integer> st, int a) { System.out.println("empty stack");
st.push(a); }
System.out.println("push(" + a + ")"); }
System.out.println("stack: " + st); }
} Output:
static void showpop(Stack<Integer> st) { stack: [ ]
System.out.print("pop -> "); push(42)
Integer a = st.pop(); stack: [42]
System.out.println(a); push(66)
System.out.println("stack: " + st); stack: [42, 66]
} push(99)
public static void main(String args[]) { stack: [42, 66, 99]
Stack<Integer> st = new Stack<Integer>(); pop -> 99
System.out.println("stack: " + st); stack: [42, 66]
showpush(st, 42); pop -> 66
showpush(st, 66); stack: [42]
showpush(st, 99); pop -> 42
showpop(st); stack: [ ]
showpop(st); pop -> empty stack
showpop(st);
Dictionary
• Given a key and value, you can store the value in a
Dictionary object.
• Once the value is stored, you can retrieve it by using
its key.
• Thus, like a map, a dictionary can be thought of as a
list of key/value pairs.
• Declared:
class Dictionary<K, V>
Here, K specifies the type of keys, and V specifies
the type of values
Hashtable
• Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
• The Hashtable constructors :
1. Hashtable( )
2. Hashtable(int size)
3. Hashtable(int size, float fillRatio)
4. Hashtable(Map m)
// Demonstrate a Hashtable. System.out.println();
import java.util.*; // Deposit 1,000 into John Doe's account.
class HTDemo { bal = balance.get("John Doe");
public static void main(String args[]) { balance.put("John Doe", bal+1000);
Hashtable<String, Double> balance = System.out.println("John Doe's new
new Hashtable<String, Double>(); balance: " +
Enumeration<String> names; balance.get("John Doe"));
String str; }
double bal; }
balance.put("John Doe", 3434.34); The output from this program is shown
balance.put("Tom Smith", 123.22); here:
balance.put("Jane Baker", 1378.00); Todd Hall: 99.22
balance.put("Tod Hall", 99.22); Ralph Smith: -19.08
balance.put("Ralph Smith", -19.08); John Doe: 3434.34
// Show all balances in hashtable. Jane Baker: 1378.0
names = balance.keys(); Tom Smith: 123.22
while(names.hasMoreElements()) { John Doe's new balance: 4434.34
str = names.nextElement();
System.out.println(str + ": " +
balance.get(str));
}
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.
• One useful capability of the Properties class is that you can
specify a default property that will be returned if no value is
associated with a certain key.
• Multiple thread can share a single properties object
without the need of external synchronisation.
• The Properties class is used by some other Java classes. For
example, it is the type of object returned by
System.getProperties( ) when obtaining environmental
values.
• Properties defines the following instance variable:
• Properties defaults; :This variable holds a default property list
associated with a Properties object.
• Properties defines these constructors:
1. Properties( )
2. Properties(Properties propDefault)
• The first version creates a Properties object that has no default
values.
• The second creates an object that uses propDefault for its default
values. In both cases, the property list is empty.
• Few methods:
• public String getProperty(String key): Returns the value associated
with key.
• A default value can be specified along with the
key in the getProperty( ) method—such as
getProperty( "name" ,"default value"). If the
"name" value is not found, then "default
value" is returned.
• Set<String> string PropertyNames( ): Returns a
set of keys.
Object setProperty(String key, String value)
Associates value with key. Returns the
previous value associated with key, or returns
null if no such association exists.
// Demonstrate a Property list. // Look for state not in list -- specify
import java.util.*; default.
class PropDemo { String str =
public static void main(String args[]) { capitals.getProperty("Florida", "Not
Properties capitals = new Properties(); Found");
capitals.put("Illinois", "Springfield"); System.out.println("The capital of Florida
capitals.put("Missouri", "Jefferson City"); is " + str + ".");
capitals.put("Washington", "Olympia"); }
capitals.put("California", "Sacramento"); }
capitals.put("Indiana", "Indianapolis"); The output from this program is shown
// Get a set-view of the keys. here:
Set<?> states = capitals.keySet(); The capital of Missouri is Jefferson City.
// Show all of the states and capitals. The capital of Illinois is Springfield.
for(Object name : states) The capital of Indiana is Indianapolis.
System.out.println("The capital of " + The capital of California is Sacramento.
name + " is " + The capital of Washington is Olympia.
capitals.getProperty((String)name) The capital of Florida is Not Found.
+ ".");
System.out.println();
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = "+entry.getValue());
• Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02 java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/ path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM file.encoding.pkg = sun.io
user.country = US user.script = sun.java.launcher = SUN_STANDARD

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy