Docsity

Collections - Introduduction to Jave Programming - Lecture Slides, Slides of Java Programming

Partial preview of the text

Download Collections - Introduduction to Jave Programming - Lecture Slides and more Slides Java Programming in PDF only on Docsity!

Collections, Maps and

Iterators

Announcements

  • Homework due today
  • Last graded lab today (and there was much rejoicing)
  • Last homework posted today, due next Monday (one week)

Map

Suppose you wanted to associate two things together For example:

  • An email address with a person
  • A student ID number with a name
  • A movie with the star actress/actor Could you do this? (See: BadMap.java)

Map

There exists a Map type to do this for you! (page 920 in book) To be general generics are used for both the key and value (key = email, value = name) (See: GoodMap.java) key (from) value (to) You should always check what code is available!

Collection

A list can have duplicates (since it is has stores elements by order), sets cannot Maps actually use both of these:

  • Keys are a set (no duplicates)
  • Values are a list (duplicates) Beware: Old code (before generics) exist, so ArrayList is different than ArrayList (See: SetExample.java)

Collection

Collection is an interface with “optional” methods This means:

  • Since abstract methods must be overridden you need to have a body
  • However, the body can just throw an exception and not do anything

Iterator

An iterator is simply something that goes over a whole list/array/set This is actually why we always use “i” “Iterator” is actually an interface, so “i” is not an Iterator but it has been acting like one

Iterators

Many pre-made Classes can return an Iterator for all of its elements

  • ArrayList
  • HashSet
  • TreeSet ... This is useful because Iterator is independent of the list type (See: UsingIterators.java)