SlideShare a Scribd company logo
9
Most read
10
Most read
13
Most read
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

More Related Content

PDF
Java Collection framework
PPSX
Collections - Maps
PDF
Collections In Java
PPSX
Collections - Lists, Sets
PPT
Java Collections Framework
PDF
Arrays in Java
PPTX
JAVA AWT
PPTX
Java Stack Data Structure.pptx
Java Collection framework
Collections - Maps
Collections In Java
Collections - Lists, Sets
Java Collections Framework
Arrays in Java
JAVA AWT
Java Stack Data Structure.pptx

What's hot (20)

PDF
Collections Api - Java
PPT
Abstract class in java
PPTX
Core java complete ppt(note)
PPTX
Inner classes in java
PPT
Final keyword in java
PDF
Generics
PPT
Method overriding
PPTX
Java - Collections framework
PPT
Java collections concept
PPT
MYSQL.ppt
PPT
JDBC – Java Database Connectivity
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
PPTX
Classes, objects in JAVA
PPTX
Operators in java
PPTX
This keyword in java
PPT
Collection Framework in java
PPSX
Collections - Array List
PPTX
Arrays in Java
Collections Api - Java
Abstract class in java
Core java complete ppt(note)
Inner classes in java
Final keyword in java
Generics
Method overriding
Java - Collections framework
Java collections concept
MYSQL.ppt
JDBC – Java Database Connectivity
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Classes, objects in JAVA
Operators in java
This keyword in java
Collection Framework in java
Collections - Array List
Arrays in Java
Ad

Viewers also liked (6)

PPT
MuleEsb Complete integration and middleware solution
PPS
СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"
PPT
Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...
PDF
Mule ESB Fundamentals
ODP
Mule ESB SMTP Connector Integration
PPTX
Mule ESB Components
MuleEsb Complete integration and middleware solution
СКБ-Банк. Игорь Клопотов. "Apache ServiceMix: опыт внедрения и эксплуатации"
Showdown: Integration Framework (Spring Integration, Apache Camel) vs. Enterp...
Mule ESB Fundamentals
Mule ESB SMTP Connector Integration
Mule ESB Components
Ad

Similar to sets and maps (20)

PPT
Java Presentation
PPT
description of Collections, seaching & Sorting
PPTX
Javasession7
PPTX
Icom4015 lecture14-f16
PPT
Java Collection slide ppt presentation..
PPTX
Java Hands-On Workshop
PPTX
Collections Training
PPT
M251_Meeting 8 (Sets and Maps_Java_).ppt
PPT
M251_Meeting 8 (SetsandMap Advanced Java).ppt
PPTX
LJ_JAVA_FS_Collection.pptx
PPT
Collections
PPTX
Java Tutorial Lab 8
PPTX
Collection and framework
PPT
Collections in Java
PPTX
Pptchdtdtfygugyxthgihhihigugufydtdfzrzrzrtdyfyfy
PPT
Collectionsand GenericsInJavaProgramming.ppt
PPT
Collections
PPT
cse403-10-Collections- iNTRODUCTION TO FRAMEWORK
PDF
hash tables for data structures and algorithm
Java Presentation
description of Collections, seaching & Sorting
Javasession7
Icom4015 lecture14-f16
Java Collection slide ppt presentation..
Java Hands-On Workshop
Collections Training
M251_Meeting 8 (Sets and Maps_Java_).ppt
M251_Meeting 8 (SetsandMap Advanced Java).ppt
LJ_JAVA_FS_Collection.pptx
Collections
Java Tutorial Lab 8
Collection and framework
Collections in Java
Pptchdtdtfygugyxthgihhihigugufydtdfzrzrzrtdyfyfy
Collectionsand GenericsInJavaProgramming.ppt
Collections
cse403-10-Collections- iNTRODUCTION TO FRAMEWORK
hash tables for data structures and algorithm

More from Rajkattamuri (20)

PPTX
Github plugin setup in anypointstudio
PPTX
For each component in mule
PPTX
Filter expression in mule
PPTX
File component in mule
PPTX
Database component in mule
PPTX
Choice component in mule
PPT
WebServices
PPTX
Java Basics in Mule
PPTX
WebServices Basic Overview
PPTX
Java For Begineers
PPT
Java Basics
PPT
WebServices Basics
PPT
Core java
PPT
WebServices SOAP WSDL and UDDI
PPTX
Web services soap
PPTX
Web services wsdl
PPTX
Web services uddi
PPT
PPTX
Mule esb dataweave
PPTX
Mule with drools
Github plugin setup in anypointstudio
For each component in mule
Filter expression in mule
File component in mule
Database component in mule
Choice component in mule
WebServices
Java Basics in Mule
WebServices Basic Overview
Java For Begineers
Java Basics
WebServices Basics
Core java
WebServices SOAP WSDL and UDDI
Web services soap
Web services wsdl
Web services uddi
Mule esb dataweave
Mule with drools

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
KodekX | Application Modernization Development
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Encapsulation theory and applications.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
KodekX | Application Modernization Development
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Spectral efficient network and resource selection model in 5G networks
Mobile App Security Testing_ A Comprehensive Guide.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Big Data Technologies - Introduction.pptx
Encapsulation theory and applications.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
cuic standard and advanced reporting.pdf
NewMind AI Monthly Chronicles - July 2025
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

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