08b: Java Collections

ICS211, Fall 2012
Dr. Zach

(switch view)

Status check

xkcd: How to Write Good Code

Joke flowchart on how to write code
from xkcd.com

Java Collections

Collection interface (ADT)

List interface (ADT)

subList Examples

From Tutorial:

List<?> list = ...
list.subList(fromIndex, toIndex).clear();

int i = list.subList(fromIndex, toIndex).indexOf(o);
int j = list.subList(fromIndex, toIndex).lastIndexOf(o);
public static <E> List<E> dealHand(List<E> deck, int n) {
    int deckSize = deck.size();
    List<E> handView = deck.subList(deckSize - n, deckSize);
    List<E> hand = new ArrayList<E>(handView);
    handView.clear();
    return hand;
}

Queue interface (ADT)

Deque interface (ADT)

Other ADTs

Also covered in Tutorial:

More stuff in java.util.concurrent too, but generally not necessary since we're not using threads

Implementations

Implementations

Others:

Using Implementations

Old Implementations

Generally don't use these. synchronized, so slight overhead to them (not as efficient)

Collections class

java.util.Arrays

    String[] cards = {"AS", "2S", "3S", "4S", "5S", ...}
    java.util.List<String> deck = java.util.Arrays.asList(cards);
    java.util.Collections.shuffle(deck);
    System.out.println(deck);                 //last two lines print same thing
    System.out.println(java.util.Arrays.toString(cards));

Implementation Help

Other useful classes: Comparator

For next time