COLLECTIONS FRAMEWORK
OVERVIEW
Collection and framework
ARRAYS
 The ARRAY class provides various methods that are useful when
working with arrays.
 The asList() method returns a List that is backed by a specified
array.
static List asList(Object []array)
binarySearch():
 To find a specified value in the given array.
 The following methods are used to apply the binarySearch(),
 static int binarySearch(byte[] array,byte value)
 static int binarySearch(char[] array,char value)
 static int binarySearch(double[] array,double value)
 static int binarySearch(int[] array,int value)
 static int binarySearch(Object[] array,Object value)
equals():
 To check whether two arrays are equal.
 The following methods are used to apply the equal(),
 static boolean equals(boolean array1[],boolean array2[])
 static boolean equals(byte array1[],byte array2[])
 static boolean equals(char array1[],char array2[])
 static boolean equals(double array1[],double array2[])
 static boolean equals(int array1[],int array2[])
Fill()
 Assigns a value to all elements in an array.
 Fills with a specified value.
 It has two versions,
 First version,
Fills an entire array,
 static void fill(boolean array[],boolean value)
 static void fill(byte array[],byte value)
 static void fill(char array[],char value)
 static void fill(double array[],double value)
Contd,
 Second version,
 Assigns a value to a subset of an array.
 static void fill(boolean array[],int start,int end,boolean value)
 static void fill(byte array[],int start,int end,byte value)
 static void fill(char array[],int start,int end,char value)
 static void fill(double array[],int start,int end,double value)
 static void fill(int array[],int start,int end,int value)
 static void fill(Object array[],int start,int end,Object value)
 Here value is assigned to the elements in array from position start to end
position.
Sort()
 Sorts an array in ascending order.
 Two versions,
 First version,
 Sorts entire array,
 Static void sort(byte array[])
 Static void sort(char array[])
 Static void sort(double array[])
 Static void sort(int array[])
 Static void sort(Object array[])
Contd,
 Second version,
 Specify a range within an array that you want to sort.
 Static void sort(byte array[],int start,int end)
 Static void sort(char array[],int start,int end)
 Static void sort(double array[],int start,int end)
 Static void sort(int array[],int start,int end)
 Static void sort(Object array[],int start,int end)
// Demonstrate Arrays
import java.util.*;
class ArraysDemo {
public static void main(String args[]) {
// allocate and initialize array
int array[] = new int[10];
for(int i = 0; i < 10; i++)
array[i] = -3 * i;
// display, sort, display
System.out.print("Original contents: ");
display(array);
Arrays.sort(array);
System.out.print("Sorted: ");
PROGRAM
display(array);
// fill and display
Arrays.fill(array, 2, 6, -1);
System.out.print("After fill(): ");
display(array);
// sort and display
Arrays.sort(array);
System.out.print("After sorting again: ");
display(array);
// binary search for -9
System.out.print("The value -9 is at location ");
int index = Arrays.binarySearch(array, -9);
System.out.println(index);
}
static void display(int array[]) {
for(int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println("");
}
}
OUTPUT:
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
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.
 To put an object on the top of the stack, call push( ).
 To remove and return the top element, call pop( ).
 An EmptyStackException is thrown if you call pop( ) when the
invoking stack is empty.
Method Description
boolean empty( ) Returns true if the stack is empty, and returns false
if the stack contains elements.
Object peek( ) Returns the element on the top of the stack, but
does not remove it.
Object pop( ) Returns the element on the top of the stack,
removing it in the process.
Object push(Object element) Pushes element onto the stack. element is also
returned.
int search(Object element) Searches for element in the stack. If found, its offset
from the top of the stack is returned. Otherwise, –1
is returned.
PROGRAM
// Demonstrate the Stack class.
import java.util.*;
class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
Output:
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
MAPS
 A map is an object that stores associations between
keys and values or key/value.
 A key must be unique and value may be duplicated.
 With help of key, value can be found easily.
 Some maps accept NULL for both key and value but not all.
Map Interface
 Map interfaces define the character and nature of maps.
 Following are interfaces support maps,
INTERFACE DESCRIPTION
Map Maps unique keys to values
Map.Entry Describes an element in a map. This is
an inner class of map.
SortedMap Extends map so that the keys are
maintained in ascending order.
Map Interface
 Map interface maps unique keys to values.
 A key is an object that is used to retrieve a value.
 Can store key and values into the map object.
 After the value is stored, it can retrieve by using its key.
 NoSuchElementException- it occurs when no items exist in
the invoking map.
 ClassCastException –it occurs when object is incompatible
with the elements.
Map Interface
 NullPointerException- it occurs when an attempt is made to
use a NULL object.
 UnsupportedOperationException- it occurs when an
attempt is made to change unmodifiable map.
 Map has two basic operations:
 get()– passing the key as an argument, the value
is returned.
 put()-it used to put a value into a map.
Method Description
void clear( ) Removes all key/value pairs from the
invoking map.
boolean containsKey(Object k) Returns true if the invoking map contains k
as a key. Otherwise, returns false.
Set entrySet( ) Returns a Set that contains the entries in the
map. The set contains objects of type
Map.Entry. This method provides a set-
view of the invoking map.
Object get(Object k) Returns the value associated with the key k.
Object put(Object k, Object v) Puts an entry in the invoking map,
overwriting any previous value associated
with the key. The key and value are k and v,
respectively. Returns null if the key did not
already exist. Otherwise, the previous value
linked to the key is returned.
Map.Entry Interfaces
 Map.entry interface enables to work with a map
entry.
 Recall entrySet() method declared by Map interface
returns a set containing the map entries.
 Each of these elements is a Map.Entry object.
SortedMap Interface
 Sorted map interface extends Map. It ensures that the entries
are maintained in ascending key order.
 Sorted map allow very efficient manipulations of
submaps(subset of maps).
 To obtain submaps use,
 headMap()
 tailMap()
 subMap()
SortedMap Interface
Class Description
Object firstKey( ) Returns the first key in the
invoking map.
Object lastKey( ) Returns the last key in the
invoking map.
SortedMap headMap(Object end) Returns a sorted map for those
map entries with keys that are
less than end.
SortedMap subMap(Object start, Object end) Returns a map containing those
entries with keys that are greater
than or equal to start and less
than end.
SortedMap tailMap(Object start) Returns a map containing those
entries with keys that are greater
than or equal to start
Map Classes
Class Description
AbstractMap Implements most of the Map interface.
EnumMap Extends AbstractMap for use with enum keys.
HashMap Extends AbstractMap to use a hash table.
TreeMap Extends AbstractMap to use a tree.
WeakHashMap Extends AbstractMap to use a hash table with
weak keys.
LinkedHashMap Extends HashMap to allow insertion-order
iterations.
IdentityHashMap Extends AbstractMap and uses reference equality
when comparing documents.
HASHMAP CLASS
 The HashMap class uses a hash table to implement the Map interface.
 The HashMap class extends AbstractMap and implements the Map
interface.
 The following constructors are defined:
 HashMap( )- constructs a default hash map.
 HashMap(Map m)- initializes the hash map by using the
elements of m.
 HashMap(int capacity)- initializes the capacity of the hash map
to capacity.
 HashMap(int capacity, float fillRatio)- initializes both the capacity
and fill ratio of the hash map by using its arguments.
PROGRAM
import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map.
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new
Double(3434.34));
hm.put("Tom Smith", new
Double(123.22));
hm.put("Jane Baker", new
Double(1378.00));
hm.put("Tod Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-
19.08));
//Get an iterator
Iterator i = set.Iterator();
While(i.hasNext()) {
Map.Entry me=(Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account.
double balance = ((Double)hm.get("John
Doe")) .doubleValue();
hm.put("John Doe",new Double( balance +
1000));
System.out.println("John Doe's new
balance: " +
hm.get("John Doe")); }}
OUTPUT:
Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Tod Hall: 99.22
Jane Baker: 1378.0
John Doe’s new balance: 4434.34
TREEMAP CLASS
 The treemap class implements the Map interface by using a tree.
 A treemap provides an efficient means of storing key/value pairs
in sorted order and allows rapid retrieval.
TREEMAP CLASS
Constructors Description
TreeMap( ) constructs an empty tree map that will be
sorted by using the natural order of its keys.
TreeMap(Map m) initializes a tree map with the entries from
m, which will be sorted by using the natural
order of the keys.
TreeMap(SortedMap sm) initializes a tree map with the entries from
sm, which will be sorted in the same order
as sm.
Tree Map Demo Program
import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
// Create a tree map.
TreeMap<String, Double> tm = new TreeMap<String, Double>();
// Put elements to the map.
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Tod Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries.
Set<Map.Entry<String, Double>> set = tm.entrySet();
// Display the elements.
for(Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account.
double balance = tm.get("John Doe");
tm.put("John Doe", balance + 1000);
System.out.println("John Doe's new balance: " +
tm.get("John Doe"));
}
}
Output:
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
LinkedHashMap Class
 LinkedHashMap extends HashMap. It maintains a linked list
of the entries in the map, in the order in which they were
inserted.
 It allows insertion-order iteration over the map. i.e.,when
iterating through a collection-view of a LinkedHashMap, the
elements will be returned in the order in which they were
inserted.
 Can create a LinkedHashMap that returns its elements in the
order in which they were last accessed
LinkedHashMap Constructors:
Constructors Description
LinkedHashMap( ) constructs a default LinkedHashMap.
LinkedHashMap(Map m) initializes the LinkedHashMap with the
elements from m.
LinkedHashMap(int capacity) initializes the capacity.
LinkedHashMap(int capacity, float fillRatio) 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.
LinkedHashMap(int capacity, float fillRatio,
boolean Order)
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
The EnumMap Class
 EnumMap extends AbstractMap and implements Map. It is
specifically for use with keys of an enum type.
 EnumMap defines the following constructors:
 EnumMap(Class Type)- creates an empty EnumMap of type
kType.
 EnumMap(Map m)- creates anEnumMap map that contains the
same entries as m.
 EnumMap(EnumMap em)- creates an EnumMap initialized with
the values in em.
REFERENCES:
 JavaTheCompleteReference,5TH ed.
 Introduction.to.Java.Programming.8th.Edition.
 www.Wikipedia.org./java/collections
QUERIES???
THANK YOU

More Related Content

DOC
Array properties
PDF
Python programming : Arrays
PDF
Arrays in python
PDF
Basic data structures in python
PPTX
Python array
PDF
Underscore.js
ODP
Collections In Scala
PDF
Arrays In Python | Python Array Operations | Edureka
Array properties
Python programming : Arrays
Arrays in python
Basic data structures in python
Python array
Underscore.js
Collections In Scala
Arrays In Python | Python Array Operations | Edureka

What's hot (20)

PDF
Collections Api - Java
PPT
Collections Framework
PDF
Collections in Java Notes
PPT
Scala collection
PDF
Scala collections
ODP
Functions In Scala
PDF
Monads and Monoids by Oleksiy Dyagilev
PDF
Java Collections API
PPT
An introduction to scala
PPT
Java Collections Framework
PDF
Arrays in python
DOCX
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
ODP
Data structures in scala
PDF
Getting Started With Scala
DOCX
Collections framework
PPT
Extractors & Implicit conversions
PPTX
Scala for curious
PDF
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Collections Api - Java
Collections Framework
Collections in Java Notes
Scala collection
Scala collections
Functions In Scala
Monads and Monoids by Oleksiy Dyagilev
Java Collections API
An introduction to scala
Java Collections Framework
Arrays in python
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Data structures in scala
Getting Started With Scala
Collections framework
Extractors & Implicit conversions
Scala for curious
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Ad

Viewers also liked (14)

PDF
Blog proyecto muebles
PDF
Referencias
PDF
Apoyo de sostenimiento
PPTX
Las Tecnologías de la Información y Comunicación
PPTX
Rantai nilai porter
PPTX
Evolución de los sistemas operativos
POT
Marketing Automation presentation for NewTech NorthWest
PPTX
El ciclo del agua
PDF
El002315
DOCX
Las Tecnologías de la Información y de la Comunicación
PPTX
Amalan baik bandar Hong Kong & bandar Kuala Terengganu
DOC
Towards Inclusive Cities: Tackling Gender based violence
PPTX
Metodologia de la Investigacion
PPTX
Los chicos e internet
Blog proyecto muebles
Referencias
Apoyo de sostenimiento
Las Tecnologías de la Información y Comunicación
Rantai nilai porter
Evolución de los sistemas operativos
Marketing Automation presentation for NewTech NorthWest
El ciclo del agua
El002315
Las Tecnologías de la Información y de la Comunicación
Amalan baik bandar Hong Kong & bandar Kuala Terengganu
Towards Inclusive Cities: Tackling Gender based violence
Metodologia de la Investigacion
Los chicos e internet
Ad

Similar to Collection and framework (20)

PPT
Basic data-structures-v.1.1
PPTX
Arrays and Strings engineering education
PDF
ReversePoem.java ---------------------------------- public cl.pdf
PPT
description of Collections, seaching & Sorting
PPT
Set_TreeSet_etc comparison in java collection.ppt
PDF
java I am trying to run my code but it is not letting me .pdf
PPT
Stack linked list
PPTX
ARRAY OPERATIONS.pptx
PPT
Collection Framework.power point presentation.......
PDF
Unit-5-Part1 Array in Python programming.pdf
PDF
Collections and generics
PPTX
Collections
PPT
PPTX
Collections in object oriented programming
DOCX
Array list
PPTX
Arrays in Java with example and types of array.pptx
PPTX
javaprograming-COLLECTION FRAMEWORK-171012084019.pptx
PPSX
javascript-Array.ppsx
PDF
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Basic data-structures-v.1.1
Arrays and Strings engineering education
ReversePoem.java ---------------------------------- public cl.pdf
description of Collections, seaching & Sorting
Set_TreeSet_etc comparison in java collection.ppt
java I am trying to run my code but it is not letting me .pdf
Stack linked list
ARRAY OPERATIONS.pptx
Collection Framework.power point presentation.......
Unit-5-Part1 Array in Python programming.pdf
Collections and generics
Collections
Collections in object oriented programming
Array list
Arrays in Java with example and types of array.pptx
javaprograming-COLLECTION FRAMEWORK-171012084019.pptx
javascript-Array.ppsx
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf

Recently uploaded (20)

PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
HVAC Specification 2024 according to central public works department
PPTX
Introduction to pro and eukaryotes and differences.pptx
PDF
My India Quiz Book_20210205121199924.pdf
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
TNA_Presentation-1-Final(SAVE)) (1).pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
AI-driven educational solutions for real-life interventions in the Philippine...
Chinmaya Tiranga quiz Grand Finale.pdf
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
A powerpoint presentation on the Revised K-10 Science Shaping Paper
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
Uderstanding digital marketing and marketing stratergie for engaging the digi...
LDMMIA Reiki Yoga Finals Review Spring Summer
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
HVAC Specification 2024 according to central public works department
Introduction to pro and eukaryotes and differences.pptx
My India Quiz Book_20210205121199924.pdf
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf

Collection and framework

  • 4. ARRAYS  The ARRAY class provides various methods that are useful when working with arrays.  The asList() method returns a List that is backed by a specified array. static List asList(Object []array)
  • 5. binarySearch():  To find a specified value in the given array.  The following methods are used to apply the binarySearch(),  static int binarySearch(byte[] array,byte value)  static int binarySearch(char[] array,char value)  static int binarySearch(double[] array,double value)  static int binarySearch(int[] array,int value)  static int binarySearch(Object[] array,Object value)
  • 6. equals():  To check whether two arrays are equal.  The following methods are used to apply the equal(),  static boolean equals(boolean array1[],boolean array2[])  static boolean equals(byte array1[],byte array2[])  static boolean equals(char array1[],char array2[])  static boolean equals(double array1[],double array2[])  static boolean equals(int array1[],int array2[])
  • 7. Fill()  Assigns a value to all elements in an array.  Fills with a specified value.  It has two versions,  First version, Fills an entire array,  static void fill(boolean array[],boolean value)  static void fill(byte array[],byte value)  static void fill(char array[],char value)  static void fill(double array[],double value)
  • 8. Contd,  Second version,  Assigns a value to a subset of an array.  static void fill(boolean array[],int start,int end,boolean value)  static void fill(byte array[],int start,int end,byte value)  static void fill(char array[],int start,int end,char value)  static void fill(double array[],int start,int end,double value)  static void fill(int array[],int start,int end,int value)  static void fill(Object array[],int start,int end,Object value)  Here value is assigned to the elements in array from position start to end position.
  • 9. Sort()  Sorts an array in ascending order.  Two versions,  First version,  Sorts entire array,  Static void sort(byte array[])  Static void sort(char array[])  Static void sort(double array[])  Static void sort(int array[])  Static void sort(Object array[])
  • 10. Contd,  Second version,  Specify a range within an array that you want to sort.  Static void sort(byte array[],int start,int end)  Static void sort(char array[],int start,int end)  Static void sort(double array[],int start,int end)  Static void sort(int array[],int start,int end)  Static void sort(Object array[],int start,int end)
  • 11. // Demonstrate Arrays import java.util.*; class ArraysDemo { public static void main(String args[]) { // allocate and initialize array int array[] = new int[10]; for(int i = 0; i < 10; i++) array[i] = -3 * i; // display, sort, display System.out.print("Original contents: "); display(array); Arrays.sort(array); System.out.print("Sorted: "); PROGRAM
  • 12. display(array); // fill and display Arrays.fill(array, 2, 6, -1); System.out.print("After fill(): "); display(array); // sort and display Arrays.sort(array); System.out.print("After sorting again: "); display(array); // binary search for -9 System.out.print("The value -9 is at location ");
  • 13. int index = Arrays.binarySearch(array, -9); System.out.println(index); } static void display(int array[]) { for(int i = 0; i < array.length; i++) System.out.print(array[i] + " "); System.out.println(""); } }
  • 14. OUTPUT: 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
  • 15. 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.  To put an object on the top of the stack, call push( ).  To remove and return the top element, call pop( ).  An EmptyStackException is thrown if you call pop( ) when the invoking stack is empty.
  • 16. Method Description boolean empty( ) Returns true if the stack is empty, and returns false if the stack contains elements. Object peek( ) Returns the element on the top of the stack, but does not remove it. Object pop( ) Returns the element on the top of the stack, removing it in the process. Object push(Object element) Pushes element onto the stack. element is also returned. int search(Object element) Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, –1 is returned.
  • 17. PROGRAM // Demonstrate the Stack class. import java.util.*; class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); }
  • 18. public static void main(String args[]) { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println("empty stack"); } } }
  • 19. Output: stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99] pop -> 99 stack: [42, 66] pop -> 66 stack: [42] pop -> 42 stack: [ ] pop -> empty stack
  • 20. MAPS  A map is an object that stores associations between keys and values or key/value.  A key must be unique and value may be duplicated.  With help of key, value can be found easily.  Some maps accept NULL for both key and value but not all.
  • 21. Map Interface  Map interfaces define the character and nature of maps.  Following are interfaces support maps, INTERFACE DESCRIPTION Map Maps unique keys to values Map.Entry Describes an element in a map. This is an inner class of map. SortedMap Extends map so that the keys are maintained in ascending order.
  • 22. Map Interface  Map interface maps unique keys to values.  A key is an object that is used to retrieve a value.  Can store key and values into the map object.  After the value is stored, it can retrieve by using its key.  NoSuchElementException- it occurs when no items exist in the invoking map.  ClassCastException –it occurs when object is incompatible with the elements.
  • 23. Map Interface  NullPointerException- it occurs when an attempt is made to use a NULL object.  UnsupportedOperationException- it occurs when an attempt is made to change unmodifiable map.  Map has two basic operations:  get()– passing the key as an argument, the value is returned.  put()-it used to put a value into a map.
  • 24. Method Description void clear( ) Removes all key/value pairs from the invoking map. boolean containsKey(Object k) Returns true if the invoking map contains k as a key. Otherwise, returns false. Set entrySet( ) Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set- view of the invoking map. Object get(Object k) Returns the value associated with the key k. Object put(Object k, Object v) Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned.
  • 25. Map.Entry Interfaces  Map.entry interface enables to work with a map entry.  Recall entrySet() method declared by Map interface returns a set containing the map entries.  Each of these elements is a Map.Entry object.
  • 26. SortedMap Interface  Sorted map interface extends Map. It ensures that the entries are maintained in ascending key order.  Sorted map allow very efficient manipulations of submaps(subset of maps).  To obtain submaps use,  headMap()  tailMap()  subMap()
  • 27. SortedMap Interface Class Description Object firstKey( ) Returns the first key in the invoking map. Object lastKey( ) Returns the last key in the invoking map. SortedMap headMap(Object end) Returns a sorted map for those map entries with keys that are less than end. SortedMap subMap(Object start, Object end) Returns a map containing those entries with keys that are greater than or equal to start and less than end. SortedMap tailMap(Object start) Returns a map containing those entries with keys that are greater than or equal to start
  • 28. Map Classes Class Description AbstractMap Implements most of the Map interface. EnumMap Extends AbstractMap for use with enum keys. HashMap Extends AbstractMap to use a hash table. TreeMap Extends AbstractMap to use a tree. WeakHashMap Extends AbstractMap to use a hash table with weak keys. LinkedHashMap Extends HashMap to allow insertion-order iterations. IdentityHashMap Extends AbstractMap and uses reference equality when comparing documents.
  • 29. HASHMAP CLASS  The HashMap class uses a hash table to implement the Map interface.  The HashMap class extends AbstractMap and implements the Map interface.  The following constructors are defined:  HashMap( )- constructs a default hash map.  HashMap(Map m)- initializes the hash map by using the elements of m.  HashMap(int capacity)- initializes the capacity of the hash map to capacity.  HashMap(int capacity, float fillRatio)- initializes both the capacity and fill ratio of the hash map by using its arguments.
  • 30. PROGRAM import java.util.*; class HashMapDemo { public static void main(String args[]) { // Create a hash map. HashMap hm = new HashMap(); // Put elements to the map hm.put("John Doe", new Double(3434.34)); hm.put("Tom Smith", new Double(123.22)); hm.put("Jane Baker", new Double(1378.00)); hm.put("Tod Hall", new Double(99.22)); hm.put("Ralph Smith", new Double(- 19.08)); //Get an iterator Iterator i = set.Iterator(); While(i.hasNext()) { Map.Entry me=(Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into John Doe's account. double balance = ((Double)hm.get("John Doe")) .doubleValue(); hm.put("John Doe",new Double( balance + 1000)); System.out.println("John Doe's new balance: " + hm.get("John Doe")); }}
  • 31. OUTPUT: Ralph Smith: -19.08 Tom Smith: 123.22 John Doe: 3434.34 Tod Hall: 99.22 Jane Baker: 1378.0 John Doe’s new balance: 4434.34
  • 32. TREEMAP CLASS  The treemap class implements the Map interface by using a tree.  A treemap provides an efficient means of storing key/value pairs in sorted order and allows rapid retrieval.
  • 33. TREEMAP CLASS Constructors Description TreeMap( ) constructs an empty tree map that will be sorted by using the natural order of its keys. TreeMap(Map m) initializes a tree map with the entries from m, which will be sorted by using the natural order of the keys. TreeMap(SortedMap sm) initializes a tree map with the entries from sm, which will be sorted in the same order as sm.
  • 34. Tree Map Demo Program import java.util.*; class TreeMapDemo { public static void main(String args[]) { // Create a tree map. TreeMap<String, Double> tm = new TreeMap<String, Double>(); // Put elements to the map. tm.put("John Doe", new Double(3434.34)); tm.put("Tom Smith", new Double(123.22)); tm.put("Jane Baker", new Double(1378.00)); tm.put("Tod Hall", new Double(99.22)); tm.put("Ralph Smith", new Double(-19.08)); // Get a set of the entries.
  • 35. Set<Map.Entry<String, Double>> set = tm.entrySet(); // Display the elements. for(Map.Entry<String, Double> me : set) { System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into John Doe's account. double balance = tm.get("John Doe"); tm.put("John Doe", balance + 1000); System.out.println("John Doe's new balance: " + tm.get("John Doe")); } }
  • 36. Output: 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
  • 37. LinkedHashMap Class  LinkedHashMap extends HashMap. It maintains a linked list of the entries in the map, in the order in which they were inserted.  It allows insertion-order iteration over the map. i.e.,when iterating through a collection-view of a LinkedHashMap, the elements will be returned in the order in which they were inserted.  Can create a LinkedHashMap that returns its elements in the order in which they were last accessed
  • 38. LinkedHashMap Constructors: Constructors Description LinkedHashMap( ) constructs a default LinkedHashMap. LinkedHashMap(Map m) initializes the LinkedHashMap with the elements from m. LinkedHashMap(int capacity) initializes the capacity. LinkedHashMap(int capacity, float fillRatio) 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. LinkedHashMap(int capacity, float fillRatio, boolean Order) 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
  • 39. The EnumMap Class  EnumMap extends AbstractMap and implements Map. It is specifically for use with keys of an enum type.  EnumMap defines the following constructors:  EnumMap(Class Type)- creates an empty EnumMap of type kType.  EnumMap(Map m)- creates anEnumMap map that contains the same entries as m.  EnumMap(EnumMap em)- creates an EnumMap initialized with the values in em.
  • 40. REFERENCES:  JavaTheCompleteReference,5TH ed.  Introduction.to.Java.Programming.8th.Edition.  www.Wikipedia.org./java/collections