Chapter 15 –The Java Collections Framework

Sections 15.1 - 15.2

An Overview of the Collections Framework

An Overview of the Collections Framework

An Overview of the Collections Framework

An Overview of the Collections Framework

An Overview of the Collections Framework

An Overview of the Collections Framework

Common Methods

Collection<String> coll = new ArrayList<>(); The ArrayList class implements the Collection
interface.

coll = new TreeSet<String>();

The TreeSet class also implements the Collection interface.

int n = coll.size();

Gets the size of the collection. n is now 0.

coll.add("Harry");
coll.add("Sally");

Adds elements to the collection.

String s = coll.toString();

Returns a string with all elements in the collection. s is now "[Harry, Sally]"

System.out.println(coll);

Invokes the toString method and prints [Harry, Sally].

coll.remove("Harry");
boolean b = coll.remove("Tom");

Checks whether this collection contains a given element. b is now true.

for (String s : coll)
   System.out.println(s);
You can use the “for each” loop with any collection. This loop prints the elements on separate lines.

Iterator<> iter = coll.iterator();

You use an iterator for visiting the elements in
the collection

Lecture 13 Clicker Question 1

You are taking a social science class and you are assigned lots of books and articles as required reading. Which data structure is best for organizing them?

  1. A set
  2. A queue
  3. A stack
  4. A map

Linked Lists

Linked Lists

Linked Lists

Linked Lists

The LinkedList Class of the Java Collections Framework

List Iterator

List Iterator

List Iterator

 

Lecture 13 Clicker Question 2

It's your turn. Complete this program so that it prints out every second element of the linked list: the elements at position 0, 2, 4, 6, 8, and so on. Use a list iterator.

What result do you get?

  1. Mary a lamb fleece white snow
  2. had little its was as
  3. An exception occurred
  4. Something else

List Iterator

A List Iterator

List Iterator

Lecture 13 Clicker Question 3

What is the contents of letters after this sequence of instructions?

List<String> letters = new LinkedList<>();
letters.add("F");
letters.add("R");
letters.add("E");
letters.add("D");
ListIterator<String> iter = letters.listIterator();
iter.next();
iter.next();
iter.remove();
iter.next();
iter.add("X");
  1. [F, R, E, X]
  2. [F, E, X, D]
  3. [F, E, R, X]
  4. Something else

List Iterator

Sample Program

section_2/ListDemo.java

Your browser does not support the <object> tag. Program Run:

Lecture 13 Clicker Question 4

It's your turn again. Complete this program so that the method removes every second element from the linked list: the elements at position 1, 3, 5, 7, 9, and so on (where, as always in Java, 0 is the starting position). Use a list iterator.

What happens?

  1. [a, lamb, fleece, white, snow] is printed
  2. [had, little, its, was, as] is printed
  3. An exception occurs
  4. Something else