SlideShare a Scribd company logo
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
Shravan Sharma
 
PDF
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
PDF
Arrays in python
Lifna C.S
 
PDF
Basic data structures in python
Lifna C.S
 
PPTX
Python array
Arnab Chakraborty
 
PDF
Underscore.js
timourian
 
ODP
Collections In Scala
Knoldus Inc.
 
PDF
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Array properties
Shravan Sharma
 
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
Arrays in python
Lifna C.S
 
Basic data structures in python
Lifna C.S
 
Python array
Arnab Chakraborty
 
Underscore.js
timourian
 
Collections In Scala
Knoldus Inc.
 
Arrays In Python | Python Array Operations | Edureka
Edureka!
 

What's hot (20)

PDF
Collections Api - Java
Drishti Bhalla
 
PPT
Collections Framework
Sunil OS
 
PDF
Collections in Java Notes
Shalabh Chaudhary
 
PPT
Scala collection
Knoldus Inc.
 
PDF
Scala collections
Inphina Technologies
 
ODP
Functions In Scala
Knoldus Inc.
 
PDF
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
PDF
Java Collections API
Alex Miller
 
PPT
An introduction to scala
Mohsen Zainalpour
 
PPT
Java Collections Framework
Sony India Software Center
 
PDF
Arrays in python
moazamali28
 
DOCX
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Sunil Kumar Gunasekaran
 
ODP
Data structures in scala
Meetu Maltiar
 
PDF
Getting Started With Scala
Meetu Maltiar
 
DOCX
Collections framework
Anand Buddarapu
 
PPT
Extractors & Implicit conversions
Knoldus Inc.
 
PPTX
Scala for curious
Tim (dev-tim) Zadorozhniy
 
PDF
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Collections Api - Java
Drishti Bhalla
 
Collections Framework
Sunil OS
 
Collections in Java Notes
Shalabh Chaudhary
 
Scala collection
Knoldus Inc.
 
Scala collections
Inphina Technologies
 
Functions In Scala
Knoldus Inc.
 
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
Java Collections API
Alex Miller
 
An introduction to scala
Mohsen Zainalpour
 
Java Collections Framework
Sony India Software Center
 
Arrays in python
moazamali28
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Sunil Kumar Gunasekaran
 
Data structures in scala
Meetu Maltiar
 
Getting Started With Scala
Meetu Maltiar
 
Collections framework
Anand Buddarapu
 
Extractors & Implicit conversions
Knoldus Inc.
 
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Ad

Viewers also liked (14)

PDF
Blog proyecto muebles
Cardumo
 
PDF
Referencias
Cardumo
 
PDF
Apoyo de sostenimiento
Cardumo
 
PPTX
Las Tecnologías de la Información y Comunicación
mvazquezda
 
PPTX
Rantai nilai porter
kelompok06
 
PPTX
Evolución de los sistemas operativos
yaranb96
 
POT
Marketing Automation presentation for NewTech NorthWest
Joe Hafner
 
PPTX
El ciclo del agua
lauracorvalan32
 
PDF
El002315
fatima giuggia
 
DOCX
Las Tecnologías de la Información y de la Comunicación
mvazquezda
 
PPTX
Amalan baik bandar Hong Kong & bandar Kuala Terengganu
balqisyaurah
 
DOC
Towards Inclusive Cities: Tackling Gender based violence
Paramita Majumdar (Ph.D)
 
PPTX
Metodologia de la Investigacion
Mainor Villarreal
 
PPTX
Los chicos e internet
Evangelina Rossi
 
Blog proyecto muebles
Cardumo
 
Referencias
Cardumo
 
Apoyo de sostenimiento
Cardumo
 
Las Tecnologías de la Información y Comunicación
mvazquezda
 
Rantai nilai porter
kelompok06
 
Evolución de los sistemas operativos
yaranb96
 
Marketing Automation presentation for NewTech NorthWest
Joe Hafner
 
El ciclo del agua
lauracorvalan32
 
El002315
fatima giuggia
 
Las Tecnologías de la Información y de la Comunicación
mvazquezda
 
Amalan baik bandar Hong Kong & bandar Kuala Terengganu
balqisyaurah
 
Towards Inclusive Cities: Tackling Gender based violence
Paramita Majumdar (Ph.D)
 
Metodologia de la Investigacion
Mainor Villarreal
 
Los chicos e internet
Evangelina Rossi
 
Ad

Similar to Collection and framework (20)

PPT
description of Collections, seaching & Sorting
mdimberu
 
PPT
STRINGS IN JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
PPTX
Java Hands-On Workshop
Arpit Poladia
 
PPT
WDD_lec_06.ppt
MuhammadAwais826180
 
PPTX
LJ_JAVA_FS_Collection.pptx
Raneez2
 
PPTX
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
PPT
Collections
Rajkattamuri
 
PPTX
Javasession7
Rajeev Kumar
 
DOC
Advanced core java
Rajeev Uppala
 
PPT
Collections in Java
Khasim Cise
 
PPT
22.ppt
BharaniDaran15
 
PPTX
AP Computer Science AP Review 2011 FRQ Questions
lipakhon2026
 
PPT
Collections
Manav Prasad
 
PPTX
Arrays and Strings engineering education
csangani1
 
PPTX
Collections Training
Ramindu Deshapriya
 
PPTX
Java 103
Manuela Grindei
 
PPTX
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
PPT
12_-_Collections_Framework
Krishna Sujeer
 
PPTX
collection framework in java
MANOJ KUMAR
 
description of Collections, seaching & Sorting
mdimberu
 
Java Hands-On Workshop
Arpit Poladia
 
WDD_lec_06.ppt
MuhammadAwais826180
 
LJ_JAVA_FS_Collection.pptx
Raneez2
 
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
Collections
Rajkattamuri
 
Javasession7
Rajeev Kumar
 
Advanced core java
Rajeev Uppala
 
Collections in Java
Khasim Cise
 
AP Computer Science AP Review 2011 FRQ Questions
lipakhon2026
 
Collections
Manav Prasad
 
Arrays and Strings engineering education
csangani1
 
Collections Training
Ramindu Deshapriya
 
Java 103
Manuela Grindei
 
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
12_-_Collections_Framework
Krishna Sujeer
 
collection framework in java
MANOJ KUMAR
 

Recently uploaded (20)

PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
CDH. pptx
AneetaSharma15
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
CDH. pptx
AneetaSharma15
 

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