SlideShare a Scribd company logo
1 of 23
Feroz Khan
 A Set is unordered and has no duplicates
 Operations are exactly those for Collection
2
int size( );
boolean isEmpty( );
boolean contains(Object e);
boolean add(Object e);
boolean remove(Object e);
Iterator iterator( );
boolean containsAll(Collection c);
boolean addAll(Collection c);
boolean removeAll(Collection c);
boolean retainAll(Collection c);
void clear( );
Object[ ] toArray( );
Object[ ] toArray(Object a[ ]);
 A set has a method Iterator iterator( ) to create an iterator
over the set
 The iterator has the usual methods:
 boolean hasNext()
 Object next()
 void remove()
 Since sets have iterators, you can also use Java 5’s
“enhanced for loop”
 remove() allows you to remove elements as you iterate
over the set
 If you change the set in any other way during iteration,
the iterator will throw a ConcurrentModificationException
3
• import java.util.*;
public class SetExample2 {
public static void main(String[] args) {
String[ ] words = { "When", "all", "is", "said", "and", "done",
"more", "has", "been", "said", "than", "done" };
Set mySet = new HashSet();
for (int i = 0; i < words.length; i++) {
mySet.add(words[i]);
}
for (Iterator iter = mySet.iterator(); iter.hasNext();) {
String word = (String) iter.next();
System.out.print(word + " ");
}
System.out.println();
}
}
• and has more When done all than said is been
4
 import java.util.*;
public class SetExample {
public static void main(String[] args) {
String[ ] words = { "When", "all", "is", "said", "and", "done",
"more", "has", "been", "said", "than", "done" };
Set<String> mySet = new HashSet<String>();
for (String word : words) {
mySet.add(word);
}
for (String word : mySet) {
System.out.print(word + " ");
}
System.out.println();
}
}
 and has more When done all than said is been
5
• Set is an interface; you can’t say new Set( )
• There are four implementations:
– HashSet is best for most purposes
– TreeSet guarantees that an iterator will return
elements in sorted order
– LinkedHashSet guarantees that guarantees that an
iterator will return elements in the order they were
inserted
– AbstractSet is a “helper” abstract class for new
implementations
• It’s poor style to expose the implementation, so:
• Good: Set s = new HashSet( );
Fair: HashSet s = new HashSet( );
6
 Testing if s2 is a subset of s1
s1.containsAll(s2)
 Setting s1 to the union of s1 and s2
s1.addAll(s2)
 Setting s1 to the intersection of s1 and s2
s1.retainAll(s2)
 Setting s1 to the set difference of s1 and s2
s1.removeAll(s2)
7
• Object.equals(Object), inherited by all
objects, really is an identity comparison
• Implementations of Set override equals so
that sets are equal if they contain the same
elements
• equals even works if two sets have different
implementations
• equals is a test on entire sets; you have to be
sure you have a working equals on
individual set elements
• hashCode has been extended similarly
– This is for sets, not elements of a collection!
8
 When testing whether a HashSet contains a given
object, Java does this:
 Java computes the hash code for the given object
 Hash codes are discussed in a separate lecture
 Java compares the given object, using equals, only with
elements in the set that have the same hash code
 Hence, an object will be considered to be in the set
only if both:
 It has the same hash code as an element in the set, and
 The equals comparison returns true
 Moral: to use a HashSet properly, you must have a
good public boolean equals(Object) and a good public
int hashCode() defined for the elements of the set
9
 A SortedSet is just like a Set, except that an
Iterator will go through it in ascending order
 SortedSet is implemented by TreeSet
10
• In a TreeSet, elements are kept in order
• That means Java must have some means of
comparing elements to decide which is
“larger” and which is “smaller”
• Java does this by using either:
– The int compareTo(Object) method of the
Comparable interface, or
– The int compare(Object, Object) method of the
Comparator interface
• Which method to use is determined when the
TreeSet is constructed
11
 new TreeSet()
 Uses the elements “natural order,” that is, it uses
compareTo(Object) from Comparable
 All elements added to this TreeSet must implement
Comparable, or you will get a ClassCastException
 new TreeSet(Comparator)
 Uses compare(Object, Object) from the given Comparator
 The Comparator specified in the constructor must be
applicable to all elements added to this TreeSet, or you will
get a ClassCastException
 Moral: to use a TreeSet properly, you must provide
the equals method and implement either Comparable
or Comparator for the elements of the set
12
• You must have a working equals(Object) and a
working hashCode() or comparison method
• If you don’t really care about iteration order,
every object inherits equals(Object) and
hashCode() from Object, and this is usually
good enough
– That is, assuming you are happy with the == test
• Strings do all this for you (they implement
equals, hashCode, and Comparable)
• Bottom line: If you don’t care about order, and
== is good enough, just use HashSet
13
• add and remove return true if they modify the
set
• Here's a trick to remove duplicates from a
Collection c:
– Collection noDups = new HashSet(c);
• A Set may not contain itself an an element
• Danger: The behavior of a set is undefined if you
change an element to be equal to another element
• Danger: A TreeSet may throw a
ConcurrentModificationException if you change
an element in the TreeSet
14
 A Map is an object that maps keys to values
 A map cannot contain duplicate keys
 Each key can map to at most one value
 Examples: dictionary, phone book, etc.
15
• Map is an interface; you can’t say new Map( )
• Here are two implementations:
– HashMap is the faster
– TreeMap guarantees the order of iteration
• It’s poor style to expose the implementation
unnecessarily, so:
• Good: Map map = new HashMap( );
Fair: HashMap map = new HashMap( );
16
Object put(Object key, Object value);
Object get(Object key);
Object remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size( );
boolean isEmpty( );
17
• If the map already contains a given key,
put(key, value) replaces the value associated
with that key
• This means Java has to do equality testing on
keys
• With a HashMap implementation, you need to
define equals and hashCode for all your keys
• With a TreeMap implementation, you need to
define equals and implement the
Comparable interface for all your keys
18
 void putAll(Map t);
 Copies one Map into another
 Example: newMap.putAll(oldMap);
 void clear();
 Example: oldMap.clear();
19
• public Set keySet( );
• public Collection values( );
• public Set entrySet( );
– returns a set of Map.Entry (key-value) pairs
• You can create iterators for the key set, the
value set, or the entry set (the set of entries,
that is, key-value pairs)
• The above views provide the only way to
iterate over a Map
20
• import java.util.*;
public class MapExample {
public static void main(String[] args) {
Map<String, String> fruit = new HashMap<String, String>();
fruit.put("Apple", "red");
fruit.put("Pear", "yellow");
fruit.put("Plum", "purple");
fruit.put("Cherry", "red");
for (String key : fruit.keySet()) {
System.out.println(key + ": " + fruit.get(key));
}
}
}
• Plum: purple
Apple: red
Pear: yellow
Cherry: red
21
 public interface Entry { // Inner interface of Map
Object getKey( );
Object getValue( );
Object setValue(Object value);
}
 This is a small interface for working with the
Collection returned by entrySet( )
 Can get elements only from the Iterator, and
they are only valid during the iteration
22
23

More Related Content

What's hot (20)

Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis
 
16 containers
16   containers16   containers
16 containers
 
Presentation1
Presentation1Presentation1
Presentation1
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
L11 array list
L11 array listL11 array list
L11 array list
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Generics
GenericsGenerics
Generics
 
Hash set (java platform se 8 )
Hash set (java platform se 8 )Hash set (java platform se 8 )
Hash set (java platform se 8 )
 
Arrays
ArraysArrays
Arrays
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
F# array searching
F#  array searchingF#  array searching
F# array searching
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
java collections
java collectionsjava collections
java collections
 

Viewers also liked

Danielle ross mfp final presentation pp
Danielle ross mfp final presentation ppDanielle ross mfp final presentation pp
Danielle ross mfp final presentation ppDanielle Ross
 
Análisis de varias leyes
Análisis de varias leyesAnálisis de varias leyes
Análisis de varias leyesyetzeniines
 
здоровый образ жизни классный час
здоровый образ жизни   классный часздоровый образ жизни   классный час
здоровый образ жизни классный часmarchuk_lidiya
 
Ahmed Nabil 2013 cv
Ahmed Nabil 2013 cvAhmed Nabil 2013 cv
Ahmed Nabil 2013 cvAhmed Nabil
 
Ficha de verificação de leitura " O cavaleiro da Dinamarca"
Ficha de verificação de leitura " O cavaleiro da Dinamarca"Ficha de verificação de leitura " O cavaleiro da Dinamarca"
Ficha de verificação de leitura " O cavaleiro da Dinamarca"Sandra Gil Miranda
 
Market research andre utkast
Market research andre utkastMarket research andre utkast
Market research andre utkastjannesandoy
 

Viewers also liked (11)

Danielle ross mfp final presentation pp
Danielle ross mfp final presentation ppDanielle ross mfp final presentation pp
Danielle ross mfp final presentation pp
 
Animals
AnimalsAnimals
Animals
 
Análisis de varias leyes
Análisis de varias leyesAnálisis de varias leyes
Análisis de varias leyes
 
здоровый образ жизни классный час
здоровый образ жизни   классный часздоровый образ жизни   классный час
здоровый образ жизни классный час
 
FINAL 2014-2015-HAF-yearbook
FINAL 2014-2015-HAF-yearbookFINAL 2014-2015-HAF-yearbook
FINAL 2014-2015-HAF-yearbook
 
Ahmed Nabil 2013 cv
Ahmed Nabil 2013 cvAhmed Nabil 2013 cv
Ahmed Nabil 2013 cv
 
Ficha de verificação de leitura " O cavaleiro da Dinamarca"
Ficha de verificação de leitura " O cavaleiro da Dinamarca"Ficha de verificação de leitura " O cavaleiro da Dinamarca"
Ficha de verificação de leitura " O cavaleiro da Dinamarca"
 
Magazine Research
Magazine ResearchMagazine Research
Magazine Research
 
Market research andre utkast
Market research andre utkastMarket research andre utkast
Market research andre utkast
 
Кейс: «Однажды в Китае», продвижение под рынок Китая
Кейс: «Однажды в Китае», продвижение под рынок КитаяКейс: «Однажды в Китае», продвижение под рынок Китая
Кейс: «Однажды в Китае», продвижение под рынок Китая
 
Szymon
SzymonSzymon
Szymon
 

Similar to Java Presentation

LJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptxLJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptxRaneez2
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
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
 
Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdfAssignment4 Assignment 4 Hashtables In this assignment we w.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdfkksrivastava1
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
18 hashing
18 hashing18 hashing
18 hashingdeonnash
 

Similar to Java Presentation (20)

sets and maps
 sets and maps sets and maps
sets and maps
 
Collections
CollectionsCollections
Collections
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Java Collections.pptx
Java Collections.pptxJava Collections.pptx
Java Collections.pptx
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
Lecture notesmap
Lecture notesmapLecture notesmap
Lecture notesmap
 
LJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptxLJ_JAVA_FS_Collection.pptx
LJ_JAVA_FS_Collection.pptx
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
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
 
Javasession7
Javasession7Javasession7
Javasession7
 
Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdfAssignment4 Assignment 4 Hashtables In this assignment we w.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
20 ch22 collections
20 ch22 collections20 ch22 collections
20 ch22 collections
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
Java collections
Java collectionsJava collections
Java collections
 
18 hashing
18 hashing18 hashing
18 hashing
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 

More from mdfkhan625

Mapping and listing with mule
Mapping and listing with muleMapping and listing with mule
Mapping and listing with mulemdfkhan625
 
How to use message properties component
How to use message properties componentHow to use message properties component
How to use message properties componentmdfkhan625
 
How to use expression filter
How to use expression filterHow to use expression filter
How to use expression filtermdfkhan625
 
Anypoint data gateway
Anypoint data gatewayAnypoint data gateway
Anypoint data gatewaymdfkhan625
 
Webservice with vm in mule
Webservice with vm in mule Webservice with vm in mule
Webservice with vm in mule mdfkhan625
 
Validating soap request in mule
Validating soap request in mule Validating soap request in mule
Validating soap request in mule mdfkhan625
 
Using xslt in mule
Using xslt in mule Using xslt in mule
Using xslt in mule mdfkhan625
 
Groovy example in mule
Groovy example in mule Groovy example in mule
Groovy example in mule mdfkhan625
 
Scatter gather flow control
Scatter gather flow control Scatter gather flow control
Scatter gather flow control mdfkhan625
 
Mule with velocity
Mule with velocity Mule with velocity
Mule with velocity mdfkhan625
 
Mule with rabbit mq
Mule with rabbit mq Mule with rabbit mq
Mule with rabbit mq mdfkhan625
 
Mule with quartz
Mule with quartzMule with quartz
Mule with quartzmdfkhan625
 
Mule with drools
Mule with drools Mule with drools
Mule with drools mdfkhan625
 
Idempotent filter with simple file
Idempotent filter with simple fileIdempotent filter with simple file
Idempotent filter with simple filemdfkhan625
 
Creating dynamic json
Creating dynamic json Creating dynamic json
Creating dynamic json mdfkhan625
 
Converting with custom transformer
Converting with custom transformer Converting with custom transformer
Converting with custom transformer mdfkhan625
 
Caching and invalidating with managed store
Caching and invalidating with managed storeCaching and invalidating with managed store
Caching and invalidating with managed storemdfkhan625
 
Cache for community edition
Cache for community edition Cache for community edition
Cache for community edition mdfkhan625
 

More from mdfkhan625 (20)

Mapping and listing with mule
Mapping and listing with muleMapping and listing with mule
Mapping and listing with mule
 
How to use message properties component
How to use message properties componentHow to use message properties component
How to use message properties component
 
How to use expression filter
How to use expression filterHow to use expression filter
How to use expression filter
 
Data weave
Data weave Data weave
Data weave
 
Anypoint data gateway
Anypoint data gatewayAnypoint data gateway
Anypoint data gateway
 
Webservice with vm in mule
Webservice with vm in mule Webservice with vm in mule
Webservice with vm in mule
 
Validating soap request in mule
Validating soap request in mule Validating soap request in mule
Validating soap request in mule
 
Using xslt in mule
Using xslt in mule Using xslt in mule
Using xslt in mule
 
Groovy example in mule
Groovy example in mule Groovy example in mule
Groovy example in mule
 
Scatter gather flow control
Scatter gather flow control Scatter gather flow control
Scatter gather flow control
 
Mule with velocity
Mule with velocity Mule with velocity
Mule with velocity
 
Mule with rabbit mq
Mule with rabbit mq Mule with rabbit mq
Mule with rabbit mq
 
Mule with quartz
Mule with quartzMule with quartz
Mule with quartz
 
Mule with drools
Mule with drools Mule with drools
Mule with drools
 
Mule esb
Mule esb Mule esb
Mule esb
 
Idempotent filter with simple file
Idempotent filter with simple fileIdempotent filter with simple file
Idempotent filter with simple file
 
Creating dynamic json
Creating dynamic json Creating dynamic json
Creating dynamic json
 
Converting with custom transformer
Converting with custom transformer Converting with custom transformer
Converting with custom transformer
 
Caching and invalidating with managed store
Caching and invalidating with managed storeCaching and invalidating with managed store
Caching and invalidating with managed store
 
Cache for community edition
Cache for community edition Cache for community edition
Cache for community edition
 

Recently uploaded

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Recently uploaded (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 

Java Presentation

  • 2.  A Set is unordered and has no duplicates  Operations are exactly those for Collection 2 int size( ); boolean isEmpty( ); boolean contains(Object e); boolean add(Object e); boolean remove(Object e); Iterator iterator( ); boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear( ); Object[ ] toArray( ); Object[ ] toArray(Object a[ ]);
  • 3.  A set has a method Iterator iterator( ) to create an iterator over the set  The iterator has the usual methods:  boolean hasNext()  Object next()  void remove()  Since sets have iterators, you can also use Java 5’s “enhanced for loop”  remove() allows you to remove elements as you iterate over the set  If you change the set in any other way during iteration, the iterator will throw a ConcurrentModificationException 3
  • 4. • import java.util.*; public class SetExample2 { public static void main(String[] args) { String[ ] words = { "When", "all", "is", "said", "and", "done", "more", "has", "been", "said", "than", "done" }; Set mySet = new HashSet(); for (int i = 0; i < words.length; i++) { mySet.add(words[i]); } for (Iterator iter = mySet.iterator(); iter.hasNext();) { String word = (String) iter.next(); System.out.print(word + " "); } System.out.println(); } } • and has more When done all than said is been 4
  • 5.  import java.util.*; public class SetExample { public static void main(String[] args) { String[ ] words = { "When", "all", "is", "said", "and", "done", "more", "has", "been", "said", "than", "done" }; Set<String> mySet = new HashSet<String>(); for (String word : words) { mySet.add(word); } for (String word : mySet) { System.out.print(word + " "); } System.out.println(); } }  and has more When done all than said is been 5
  • 6. • Set is an interface; you can’t say new Set( ) • There are four implementations: – HashSet is best for most purposes – TreeSet guarantees that an iterator will return elements in sorted order – LinkedHashSet guarantees that guarantees that an iterator will return elements in the order they were inserted – AbstractSet is a “helper” abstract class for new implementations • It’s poor style to expose the implementation, so: • Good: Set s = new HashSet( ); Fair: HashSet s = new HashSet( ); 6
  • 7.  Testing if s2 is a subset of s1 s1.containsAll(s2)  Setting s1 to the union of s1 and s2 s1.addAll(s2)  Setting s1 to the intersection of s1 and s2 s1.retainAll(s2)  Setting s1 to the set difference of s1 and s2 s1.removeAll(s2) 7
  • 8. • Object.equals(Object), inherited by all objects, really is an identity comparison • Implementations of Set override equals so that sets are equal if they contain the same elements • equals even works if two sets have different implementations • equals is a test on entire sets; you have to be sure you have a working equals on individual set elements • hashCode has been extended similarly – This is for sets, not elements of a collection! 8
  • 9.  When testing whether a HashSet contains a given object, Java does this:  Java computes the hash code for the given object  Hash codes are discussed in a separate lecture  Java compares the given object, using equals, only with elements in the set that have the same hash code  Hence, an object will be considered to be in the set only if both:  It has the same hash code as an element in the set, and  The equals comparison returns true  Moral: to use a HashSet properly, you must have a good public boolean equals(Object) and a good public int hashCode() defined for the elements of the set 9
  • 10.  A SortedSet is just like a Set, except that an Iterator will go through it in ascending order  SortedSet is implemented by TreeSet 10
  • 11. • In a TreeSet, elements are kept in order • That means Java must have some means of comparing elements to decide which is “larger” and which is “smaller” • Java does this by using either: – The int compareTo(Object) method of the Comparable interface, or – The int compare(Object, Object) method of the Comparator interface • Which method to use is determined when the TreeSet is constructed 11
  • 12.  new TreeSet()  Uses the elements “natural order,” that is, it uses compareTo(Object) from Comparable  All elements added to this TreeSet must implement Comparable, or you will get a ClassCastException  new TreeSet(Comparator)  Uses compare(Object, Object) from the given Comparator  The Comparator specified in the constructor must be applicable to all elements added to this TreeSet, or you will get a ClassCastException  Moral: to use a TreeSet properly, you must provide the equals method and implement either Comparable or Comparator for the elements of the set 12
  • 13. • You must have a working equals(Object) and a working hashCode() or comparison method • If you don’t really care about iteration order, every object inherits equals(Object) and hashCode() from Object, and this is usually good enough – That is, assuming you are happy with the == test • Strings do all this for you (they implement equals, hashCode, and Comparable) • Bottom line: If you don’t care about order, and == is good enough, just use HashSet 13
  • 14. • add and remove return true if they modify the set • Here's a trick to remove duplicates from a Collection c: – Collection noDups = new HashSet(c); • A Set may not contain itself an an element • Danger: The behavior of a set is undefined if you change an element to be equal to another element • Danger: A TreeSet may throw a ConcurrentModificationException if you change an element in the TreeSet 14
  • 15.  A Map is an object that maps keys to values  A map cannot contain duplicate keys  Each key can map to at most one value  Examples: dictionary, phone book, etc. 15
  • 16. • Map is an interface; you can’t say new Map( ) • Here are two implementations: – HashMap is the faster – TreeMap guarantees the order of iteration • It’s poor style to expose the implementation unnecessarily, so: • Good: Map map = new HashMap( ); Fair: HashMap map = new HashMap( ); 16
  • 17. Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size( ); boolean isEmpty( ); 17
  • 18. • If the map already contains a given key, put(key, value) replaces the value associated with that key • This means Java has to do equality testing on keys • With a HashMap implementation, you need to define equals and hashCode for all your keys • With a TreeMap implementation, you need to define equals and implement the Comparable interface for all your keys 18
  • 19.  void putAll(Map t);  Copies one Map into another  Example: newMap.putAll(oldMap);  void clear();  Example: oldMap.clear(); 19
  • 20. • public Set keySet( ); • public Collection values( ); • public Set entrySet( ); – returns a set of Map.Entry (key-value) pairs • You can create iterators for the key set, the value set, or the entry set (the set of entries, that is, key-value pairs) • The above views provide the only way to iterate over a Map 20
  • 21. • import java.util.*; public class MapExample { public static void main(String[] args) { Map<String, String> fruit = new HashMap<String, String>(); fruit.put("Apple", "red"); fruit.put("Pear", "yellow"); fruit.put("Plum", "purple"); fruit.put("Cherry", "red"); for (String key : fruit.keySet()) { System.out.println(key + ": " + fruit.get(key)); } } } • Plum: purple Apple: red Pear: yellow Cherry: red 21
  • 22.  public interface Entry { // Inner interface of Map Object getKey( ); Object getValue( ); Object setValue(Object value); }  This is a small interface for working with the Collection returned by entrySet( )  Can get elements only from the Iterator, and they are only valid during the iteration 22
  • 23. 23