SlideShare a Scribd company logo
1 of 42
COLLECTIONS FRAMEWORK
OVERVIEW
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

What's hot

Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevJavaDayUA
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonmoazamali28
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Sunil Kumar Gunasekaran
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scalaMeetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversionsKnoldus Inc.
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
 

What's hot (20)

Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Scala collection
Scala collectionScala collection
Scala collection
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Lec2
Lec2Lec2
Lec2
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Collections framework
Collections frameworkCollections framework
Collections framework
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversions
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 

Viewers also liked

Blog proyecto muebles
Blog proyecto mueblesBlog proyecto muebles
Blog proyecto mueblesCardumo
 
Referencias
ReferenciasReferencias
ReferenciasCardumo
 
Apoyo de sostenimiento
Apoyo de sostenimientoApoyo de sostenimiento
Apoyo de sostenimientoCardumo
 
Las Tecnologías de la Información y Comunicación
Las Tecnologías de la Información y ComunicaciónLas Tecnologías de la Información y Comunicación
Las Tecnologías de la Información y Comunicaciónmvazquezda
 
Rantai nilai porter
Rantai nilai porterRantai nilai porter
Rantai nilai porterkelompok06
 
Evolución de los sistemas operativos
Evolución  de los sistemas operativosEvolución  de los sistemas operativos
Evolución de los sistemas operativosyaranb96
 
Marketing Automation presentation for NewTech NorthWest
Marketing Automation presentation for NewTech NorthWestMarketing Automation presentation for NewTech NorthWest
Marketing Automation presentation for NewTech NorthWestJoe Hafner
 
Las Tecnologías de la Información y de la Comunicación
Las Tecnologías de la Información y de la ComunicaciónLas Tecnologías de la Información y de la Comunicación
Las Tecnologías de la Información y de la Comunicaciónmvazquezda
 
Amalan baik bandar Hong Kong & bandar Kuala Terengganu
Amalan baik bandar Hong Kong & bandar Kuala TerengganuAmalan baik bandar Hong Kong & bandar Kuala Terengganu
Amalan baik bandar Hong Kong & bandar Kuala Terengganubalqisyaurah
 
Towards Inclusive Cities: Tackling Gender based violence
Towards Inclusive Cities: Tackling Gender based violenceTowards Inclusive Cities: Tackling Gender based violence
Towards Inclusive Cities: Tackling Gender based violenceParamita Majumdar (Ph.D)
 
Metodologia de la Investigacion
Metodologia de la InvestigacionMetodologia de la Investigacion
Metodologia de la InvestigacionMainor Villarreal
 

Viewers also liked (14)

Blog proyecto muebles
Blog proyecto mueblesBlog proyecto muebles
Blog proyecto muebles
 
Referencias
ReferenciasReferencias
Referencias
 
Apoyo de sostenimiento
Apoyo de sostenimientoApoyo de sostenimiento
Apoyo de sostenimiento
 
Las Tecnologías de la Información y Comunicación
Las Tecnologías de la Información y ComunicaciónLas Tecnologías de la Información y Comunicación
Las Tecnologías de la Información y Comunicación
 
Rantai nilai porter
Rantai nilai porterRantai nilai porter
Rantai nilai porter
 
Evolución de los sistemas operativos
Evolución  de los sistemas operativosEvolución  de los sistemas operativos
Evolución de los sistemas operativos
 
Marketing Automation presentation for NewTech NorthWest
Marketing Automation presentation for NewTech NorthWestMarketing Automation presentation for NewTech NorthWest
Marketing Automation presentation for NewTech NorthWest
 
El ciclo del agua
El ciclo del aguaEl ciclo del agua
El ciclo del agua
 
El002315
El002315El002315
El002315
 
Las Tecnologías de la Información y de la Comunicación
Las Tecnologías de la Información y de la ComunicaciónLas Tecnologías de la Información y de la Comunicación
Las Tecnologías de la Información y de la Comunicación
 
Amalan baik bandar Hong Kong & bandar Kuala Terengganu
Amalan baik bandar Hong Kong & bandar Kuala TerengganuAmalan baik bandar Hong Kong & bandar Kuala Terengganu
Amalan baik bandar Hong Kong & bandar Kuala Terengganu
 
Towards Inclusive Cities: Tackling Gender based violence
Towards Inclusive Cities: Tackling Gender based violenceTowards Inclusive Cities: Tackling Gender based violence
Towards Inclusive Cities: Tackling Gender based violence
 
Metodologia de la Investigacion
Metodologia de la InvestigacionMetodologia de la Investigacion
Metodologia de la Investigacion
 
Los chicos e internet
Los chicos e internetLos chicos e internet
Los chicos e internet
 

Similar to Collection and framework

ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdfadinathassociates
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
ARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxDarellMuchoko
 
javascript-Array.ppsx
javascript-Array.ppsxjavascript-Array.ppsx
javascript-Array.ppsxVedantSaraf9
 
Data Structures in javaScript 2015
Data Structures in javaScript 2015Data Structures in javaScript 2015
Data Structures in javaScript 2015Nir Kaufman
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxhemanth248901
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 

Similar to Collection and framework (20)

Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
ARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptx
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
Collections
CollectionsCollections
Collections
 
22.ppt
22.ppt22.ppt
22.ppt
 
Lec2
Lec2Lec2
Lec2
 
Array list
Array listArray list
Array list
 
javascript-Array.ppsx
javascript-Array.ppsxjavascript-Array.ppsx
javascript-Array.ppsx
 
Data Structures in javaScript 2015
Data Structures in javaScript 2015Data Structures in javaScript 2015
Data Structures in javaScript 2015
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Lec3
Lec3Lec3
Lec3
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptx
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
collections
collectionscollections
collections
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
java set1 program.pdf
java set1 program.pdfjava set1 program.pdf
java set1 program.pdf
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 

Recently uploaded

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 

Recently uploaded (20)

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 

Collection and framework

  • 3.
  • 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