C6: Implementing Collections and Maps
CPSC 210
Learning Goals
- Gain an overview over Java collections
- Use the Map<K, V> type in the Java library
- Select the appropriate collection type from the Java library
Java Collections
Collection
Map
Iterable
List
Queue
Set
HashMap
HashSet
ArrayList
LinkedList
...
has
Maps
-
Map<K, V> interface with two type parameters:
- K - represents the type for the key
- V - represents the type for the value
- In this course we will focus on HashMap<K, V>
- You have seen a collection of key-value pairs using a binary search tree in CPSC 110
HashMap Example
"Firas" |
"Felix" |
"Taryn" |
Map<String, Instructor>
Map<K, V>
values: instructor objects
keys: names
Map<String, Instructor> instructors;
instructors = new HashMap<String, Instructor>();
instructors.put("Firas", new Instructor());
instructors.put("Felix", new Instructor());
instructors.put("Taryn", new Instructor());
Instructor firas = instructors.get("Firas");
Instructor felix = instructors.get("Felix");
Instructor taryn = instructors.get("Taryn");
Which Collection to Use?
Which one to use? (2)
- Lists: for maintaining the order in which items were added
- Sets: if there are no duplicate items in the collection
- Maps: to represent collections of key-value pairs
HashSet
ArrayList
LinkedList
HashMap
Lecture Ticket C6
public class Section {
private Collection<Topic> topics;
public Section(Collection<Topic> topics) {
this.topics = topics;
}
}
public class Topic {
private Text text;
private Video video;
// REQUIRIES text and video to be non-null
public Topic(Text text, Video video) {
this.text = text;
this.video = video;
}
}
Lecture Lab
Lecture Lab
C6: Implementing Collections and Maps
The End - Thank You!
C6 Working with Collections
By firas_moosvi
C6 Working with Collections
- 120