SlideShare a Scribd company logo
JAVA
The Set interface
• 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[ ]);
Iterators for sets
• 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
Iterating through a Set (Java 1.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
Iterating through a Set (Java 5.0)
• 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 implementations
• 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
Typical set operations
• 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
Set equality
• 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
Membership testing in HashSets
• 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
The SortedSet interface
• A SortedSet is just like a Set, except that an
Iterator will go through it in ascending order
• SortedSet is implemented by TreeSet
10
Membership testing in TreeSets
• 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
Comparisons for TreeSets
• 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
How hard is it to use a Set?
• 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
Set tips
• 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
The Map interface
• 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 implementations
• 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
Map: Basic operations
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
More about put
• 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
Map: Bulk operations
• void putAll(Map t);
– Copies one Map into another
– Example: newMap.putAll(oldMap);
• void clear();
– Example: oldMap.clear();
19
Map: Collection views
• 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
Map example
• 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
Map.Entry
Interface for entrySet elements
• 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
The End
23
Ad

More Related Content

What's hot (20)

Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
Hitesh-Java
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in java
Ramakrishna Joshi
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
L11 array list
L11 array listL11 array list
L11 array list
teach4uin
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
Sets in python
Sets in pythonSets in python
Sets in python
baabtra.com - No. 1 supplier of quality freshers
 

Viewers also liked (6)

MuleEsb Complete integration and middleware solution
MuleEsb Complete integration and middleware solutionMuleEsb Complete integration and middleware solution
MuleEsb Complete integration and middleware solution
Rajkattamuri
 
СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"
СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"
СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"
Expolink
 
Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...
Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...
Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...
Kai Wähner
 
Mule ESB Fundamentals
Mule ESB FundamentalsMule ESB Fundamentals
Mule ESB Fundamentals
Naresh Chintalcheru
 
Mule ESB SMTP Connector Integration
Mule ESB SMTP Connector  IntegrationMule ESB SMTP Connector  Integration
Mule ESB SMTP Connector Integration
AnilKumar Etagowni
 
Mule ESB Components
Mule ESB Components Mule ESB Components
Mule ESB Components
pat_91
 
MuleEsb Complete integration and middleware solution
MuleEsb Complete integration and middleware solutionMuleEsb Complete integration and middleware solution
MuleEsb Complete integration and middleware solution
Rajkattamuri
 
СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"
СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"
СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"
Expolink
 
Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...
Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...
Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...
Kai Wähner
 
Mule ESB SMTP Connector Integration
Mule ESB SMTP Connector  IntegrationMule ESB SMTP Connector  Integration
Mule ESB SMTP Connector Integration
AnilKumar Etagowni
 
Mule ESB Components
Mule ESB Components Mule ESB Components
Mule ESB Components
pat_91
 
Ad

Similar to sets and maps (20)

Java
JavaJava
Java
AbdulImrankhan7
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
mdfkhan625
 
Set_TreeSet_etc comparison in java collection.ppt
Set_TreeSet_etc comparison in java collection.pptSet_TreeSet_etc comparison in java collection.ppt
Set_TreeSet_etc comparison in java collection.ppt
22ad0301
 
Collections Training
Collections TrainingCollections Training
Collections Training
Ramindu Deshapriya
 
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
agorolabs
 
Java Collection slide ppt presentation..
Java Collection slide ppt presentation..Java Collection slide ppt presentation..
Java Collection slide ppt presentation..
madduriradha
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Collections
CollectionsCollections
Collections
Manav Prasad
 
Collections
CollectionsCollections
Collections
Rajkattamuri
 
Java Collections.pptx
Java Collections.pptxJava Collections.pptx
Java Collections.pptx
AbhishekKudal2
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
BienvenidoVelezUPR
 
Collections
CollectionsCollections
Collections
sagsharma
 
collectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptxcollectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
Muthukumaran Subramanian
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
Set data structure
Set data structure Set data structure
Set data structure
Tech_MX
 
Topic-G-JavaCollections Framework.ppt
Topic-G-JavaCollections    Framework.pptTopic-G-JavaCollections    Framework.ppt
Topic-G-JavaCollections Framework.ppt
swapnilslide2019
 
Javasession7
Javasession7Javasession7
Javasession7
Rajeev Kumar
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
Kenji HASUNUMA
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
mdfkhan625
 
Set_TreeSet_etc comparison in java collection.ppt
Set_TreeSet_etc comparison in java collection.pptSet_TreeSet_etc comparison in java collection.ppt
Set_TreeSet_etc comparison in java collection.ppt
22ad0301
 
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
agorolabs
 
Java Collection slide ppt presentation..
Java Collection slide ppt presentation..Java Collection slide ppt presentation..
Java Collection slide ppt presentation..
madduriradha
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
collectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptxcollectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
Set data structure
Set data structure Set data structure
Set data structure
Tech_MX
 
Topic-G-JavaCollections Framework.ppt
Topic-G-JavaCollections    Framework.pptTopic-G-JavaCollections    Framework.ppt
Topic-G-JavaCollections Framework.ppt
swapnilslide2019
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
Kenji HASUNUMA
 
Ad

More from Rajkattamuri (20)

Github plugin setup in anypointstudio
Github plugin setup in anypointstudioGithub plugin setup in anypointstudio
Github plugin setup in anypointstudio
Rajkattamuri
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
Rajkattamuri
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
Rajkattamuri
 
File component in mule
File component in muleFile component in mule
File component in mule
Rajkattamuri
 
Database component in mule
Database component in muleDatabase component in mule
Database component in mule
Rajkattamuri
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
Rajkattamuri
 
WebServices
WebServicesWebServices
WebServices
Rajkattamuri
 
Java Basics in Mule
Java Basics in MuleJava Basics in Mule
Java Basics in Mule
Rajkattamuri
 
WebServices Basic Overview
WebServices Basic OverviewWebServices Basic Overview
WebServices Basic Overview
Rajkattamuri
 
Java For Begineers
Java For BegineersJava For Begineers
Java For Begineers
Rajkattamuri
 
Java Basics
Java BasicsJava Basics
Java Basics
Rajkattamuri
 
WebServices Basics
WebServices BasicsWebServices Basics
WebServices Basics
Rajkattamuri
 
Core java
Core javaCore java
Core java
Rajkattamuri
 
WebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIWebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDI
Rajkattamuri
 
Web services soap
Web services soapWeb services soap
Web services soap
Rajkattamuri
 
Web services wsdl
Web services wsdlWeb services wsdl
Web services wsdl
Rajkattamuri
 
Web services uddi
Web services uddiWeb services uddi
Web services uddi
Rajkattamuri
 
Maven
MavenMaven
Maven
Rajkattamuri
 
Mule esb dataweave
Mule esb dataweaveMule esb dataweave
Mule esb dataweave
Rajkattamuri
 
Mule with drools
Mule with drools Mule with drools
Mule with drools
Rajkattamuri
 
Github plugin setup in anypointstudio
Github plugin setup in anypointstudioGithub plugin setup in anypointstudio
Github plugin setup in anypointstudio
Rajkattamuri
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
Rajkattamuri
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
Rajkattamuri
 
File component in mule
File component in muleFile component in mule
File component in mule
Rajkattamuri
 
Database component in mule
Database component in muleDatabase component in mule
Database component in mule
Rajkattamuri
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
Rajkattamuri
 
Java Basics in Mule
Java Basics in MuleJava Basics in Mule
Java Basics in Mule
Rajkattamuri
 
WebServices Basic Overview
WebServices Basic OverviewWebServices Basic Overview
WebServices Basic Overview
Rajkattamuri
 
Java For Begineers
Java For BegineersJava For Begineers
Java For Begineers
Rajkattamuri
 
WebServices Basics
WebServices BasicsWebServices Basics
WebServices Basics
Rajkattamuri
 
WebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIWebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDI
Rajkattamuri
 
Mule esb dataweave
Mule esb dataweaveMule esb dataweave
Mule esb dataweave
Rajkattamuri
 

Recently uploaded (20)

Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 

sets and maps

  • 2. The Set interface • 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. Iterators for sets • 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. Iterating through a Set (Java 1.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. Iterating through a Set (Java 5.0) • 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 implementations • 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. Typical set operations • 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. Set equality • 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. Membership testing in HashSets • 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. The SortedSet interface • 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. Membership testing in TreeSets • 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. Comparisons for TreeSets • 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. How hard is it to use a Set? • 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. Set tips • 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. The Map interface • 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 implementations • 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. Map: Basic operations 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. More about put • 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. Map: Bulk operations • void putAll(Map t); – Copies one Map into another – Example: newMap.putAll(oldMap); • void clear(); – Example: oldMap.clear(); 19
  • 20. Map: Collection views • 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. Map example • 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. Map.Entry Interface for entrySet elements • 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