C6: Working with Collections

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

Map<String, Instructor>
Map<K, V>

values: instructor objects

keys: names

Map<String, Instructor> instructors;
instructors = new HashMap<String, Instructor>();
instructors.put("Felix", new Instructor());
instructors.put("Steve", new Instructor());
instructors.put("Meghan", new Instructor());
Instructor felix = instructors.get("Felix");
Instructor steve = instructors.get("Steve");
Instructor meghan = instructors.get("Meghan");

"Felix"

"Steve"

"Meghan"

Which Collection to Use?

Also preserves order.

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;

  public Topic(Text text, Video video) {
    this.text = text;
    this.video = video;
  }
}

C6: Working with Collections

The End - Thank You!

C6 Working with Collections

By Steven Wolfman

C6 Working with Collections

  • 3