1.07k likes | 1.31k Views
Lists and the Collection Interface. Chapter 4. Chapter Objectives. To become familiar with the List interface To understand how to write an array-based implementation of the List interface To study the difference between single-, double-, and circular linked list data structures
E N D
Lists and the Collection Interface Chapter 4
Chapter Objectives • To become familiar with the List interface • To understand how to write an array-based implementation of the List interface • To study the difference between single-, double-, and circular linked list data structures • To learn how to implement the List interface using a linked-list • To understand the Iterator interface Chapter 4: Lists and the Collection Interface
Chapter Objective (continued) • To learn how to implement the iterator for a linked list • To become familiar with the Java Collection framework Chapter 4: Lists and the Collection Interface
The List Interface and ArrayList Class • An array is an indexed structure: can select its elements in arbitrary order using a subscript value • Elements may be accessed in sequence using a loop that increments the subscript • Disadvantages of arrays: You cannot • Increase or decrease the length • Add an element at a specified position without shifting the other elements to make room • Remove an element at a specified position without shifting other elements to fill in the resulting gap Chapter 4: Lists and the Collection Interface
The List Interface and ArrayList Class (continued) • Allowed operations on the List interface include: • Finding a specified target • Adding an element to either end • Removing an item from either end • Traversing the list structure without a subscript • Not all classes perform the allowed operations with the same degree of efficiency • An array provides the ability to store primitive-type data whereas the List classes all store references to Objects. Autoboxing facilitates this. Chapter 4: Lists and the Collection Interface
The List Interface and ArrayList Class (continued) Chapter 4: Lists and the Collection Interface
The ArrayList Class • Simplest class that implements the List interface • “Improvement” over an array object • Used when a programmer wants to add new elements to the end of a list but still needs the capability to access the elements stored in the list in arbitrary order • For example: List<String> myList = new ArrayList<String>(); myList.add(“Bashful”); myList.add(“Awful”); myList.add(“Jumpy”); myList.add(“Happy”); Chapter 4: Lists and the Collection Interface
The ArrayList Class • Then • After myList.add(2, “Doc”); • After myList.add(“Dopey”); Chapter 4: Lists and the Collection Interface
The ArrayList Class (continued) • Suppose we have • Then myList.remove(1); • And myList.set(2, “Sneezy”); Chapter 4: Lists and the Collection Interface
Generic Collections • Language feature introduced in Java 5.0 called generic collections (or generics) • Generics allow you to define a collection that contains references to objects of one specific type • List<String> myList = new ArrayList<String>(); specifies that myList is a List of String where String is a type parameter • Only references to objects of type String can be stored in myList, and all items retrieved are of type String. • A type parameter is analogous to a method parameter. Chapter 4: Lists and the Collection Interface
Generic Collections • In Java, a non-generic collection is more general than a generic collection • Non-generic collection can store objects of different data types • In a generic collection, all objects must be of same type Chapter 4: Lists and the Collection Interface
Creating a Generic Collection Chapter 4: Lists and the Collection Interface
Non-generic Example • For example ArrayList yourList = new ArrayList(); yourList.add(new Integer(35));// element 0 is Integer yourList.add(“bunny”); // element 1 is String yourList.add(new Double(3.14));// element 2 is Double • Will this work? String animal = yourList.get(1); • Syntax error: incompatible types, since it is an Object • Must cast: String animal = (String) yourList.get(1); • Consider: String aTwo = (String) yourList.get(2); • Will compile, but gives runtime error… • This is bad! Chapter 4: Lists and the Collection Interface
Generics • Advantages include… • Type incompatibility detected at compile time • Downcasting not necessary • Specific data types (e.g., String), not Object • The book likes generics • Book suggests you only use non-generics if need to store objects of different types in same collection Chapter 4: Lists and the Collection Interface
Specification of the ArrayList Class Chapter 4: Lists and the Collection Interface
Application of ArrayList • The ArrayList gives you additional capability beyond what an array provides • Combining Autoboxing with Generic Collections you can store and retrieve primitive data types when working with an ArrayList • Section 4.2 gives some examples • Phone Directory using ArrayList instead of array • Read Section 4.2 • It’s only 2 pages! Chapter 4: Lists and the Collection Interface
KWArrayList Class • Authors implement their our own ArrayList class • Call it KWArrayList • Why are they doing this? • Illustrates how class actually works (not in every detail, but the basic ideas) • Can analyze the work involved • This work is all hidden when using ArrayList Chapter 4: Lists and the Collection Interface
KWArrayList Class • KWArrayList is author’s implementation of an ArrayList class • Physical size of array indicated by data field capacity • Number of data items indicated by the data field size Chapter 4: Lists and the Collection Interface
KWArrayList Class Definition publicclass KWArrayList < E > { // Data Fields /** The default initial capacity */ privatestaticfinalint INITIAL_CAPACITY = 10; /** The underlying data array */ private E[] theData; /** The current size */ privateint size = 0; /** The current capacity */ privateint capacity = 0; . . . . . Chapter 4: Lists and the Collection Interface
KWArrayList Class Constructor public KWArrayList() { capacity = INITIAL_CAPACITY; theData = (E[]) new Object[capacity]; } • Note that theData = (E[]) new Object[capacity]; causes compiler to issue warning message: KWListArray.java uses unchecked or unsafe operations • Why? Chapter 4: Lists and the Collection Interface
KWArrayList Class Constructor (Again) public KWArrayList() { capacity = INITIAL_CAPACITY; theData = (E[]) new Object[capacity]; } • Suppose that instead we use theData = new E[capacity]; • Will this work? • No, since type of E is not known at compile time, so must create general Object and downcast Chapter 4: Lists and the Collection Interface
Add(E anEntry) Method • The algorithm… • Insert new item at position indicated by size • Increment the value of size • Return true to indicate success • The picture… Chapter 4: Lists and the Collection Interface
Add(E anEntry) Method • The code… publicboolean add(E anEntry) { if (size == capacity) { reallocate(); } theData[size] = anEntry; size++; returntrue; } • Would this work? theData[size++] = anEntry; Chapter 4: Lists and the Collection Interface
Add(int index,E anEntry) Method • The algorithm… • Make room by shifting data elements “up” • Insert anEntry at position index • The picture… Chapter 4: Lists and the Collection Interface
Add(int index,E anEntry) Method • The code… publicvoid add(int index, E anEntry) { if (index < 0 || index > size) { throw new ArrayIndexOutOfBoundsException(index); } if (size == capacity) { reallocate(); } for (int i = size; i > index; i--) { theData[i] = theData[i - 1]; } theData[index] = anEntry; size++; } Chapter 4: Lists and the Collection Interface
set Method • The algorithm and picture are fairly obvious… • The code… public E set(int index, E newValue) { if (index < 0 || index >= size) { thrownew ArrayIndexOutOfBoundsException(index); } E oldValue = theData[index]; theData[index] = newValue; return oldValue; } Chapter 4: Lists and the Collection Interface
get Method • The algorithm and picture are even more obvious… • The code… public E get(int index) { if (index < 0 || index >= size) { thrownew ArrayIndexOutOfBoundsException(index); } return theData[index]; } Chapter 4: Lists and the Collection Interface
remove Method • The algorithm… • Remove element • Shift “down” to fill in the gap • The picture… Chapter 4: Lists and the Collection Interface
remove Method • The code… public E remove(int index) { if (index < 0 || index >= size) { thrownew ArrayIndexOutOfBoundsException(index); } E returnValue = theData[index]; for (int i = index + 1; i < size; i++) { theData[i - 1] = theData[i]; } size--; return returnValue; } Chapter 4: Lists and the Collection Interface
reallocate Method • The algorithm… • Double the size of the underlying array • The picture… • Not necessary! • The code… privatevoid reallocate() { capacity = 2 * capacity; E[] newData = (E[]) new Object[capacity]; System.arraycopy(theData, 0, newData, 0, size); theData = newData; } Chapter 4: Lists and the Collection Interface
KWArrayList as Collection of Objects • Suppose we don’t want a generic collection… publicclass KWArrayList { // Data Fields /** The default initial capacity */ privatestaticfinalint INITIAL_CAPACITY = 10; /** The current size */ privateint size = 0; . . . . . • And each reference to type E[] is now Object[] /** The underlying data array */ private Object[] theData; Chapter 4: Lists and the Collection Interface
Performance of KWArrayList • Set and get methods execute in constant time • No loops, so O(1) • Inserting or removing elements is linear time • Shift (at most) n elements, so O(n) • What about reallocate? Chapter 4: Lists and the Collection Interface
Vector Class • Initial release of Java API contained the Vector class which has similar functionality to the ArrayList • Both contain the same methods • New applications should use ArrayList rather than Vector • The Stack class is a subclass of Vector • But Stack class is actually useful (next chapter…) Chapter 4: Lists and the Collection Interface
ArrayList Limitation • Suppose we have a (virtual) line of 4 students • Give each student a number, 0 thru 3 • Where number represents position in line • For example: Bob (0), Alice (1), Eve (2), Charlie (3) • Suppose Alice leaves • Then Eve and Charlie must be “renumbered” • In general, this is O(n) operation • This is what happens with ArrayList remove • Behind the scenes, of course • Is there a better way? Chapter 4: Lists and the Collection Interface
Linked Lists • Again, suppose we have a (virtual) line of 4 students • Instead of numbering… • Tell each student who is behind them • For example: Bob Alice Eve Charlie • Bob knows Alice is behind him, etc. • Now suppose Alice leaves the line • Only Bob needs to make a change • Bob Eve Charlie • How to implement this linked list data structure? Chapter 4: Lists and the Collection Interface
Linked Lists • The ArrayListadd and remove methods operate in linear time because loop shift elements in an array • Linked list overcomes this by providing ability to add or remove items anywhere in the list in constant time • Each element (node) in a linked list stores information and a link to the next node • This is known as a single-linked list • In a double-linked list, each node has a link to the next node and a link to the previous node Chapter 4: Lists and the Collection Interface
List Node • A node contains a data item and one or more links • A link is a reference to a node • A node class generally defined inside another class • Inner class: node details should be private • Recall, private is visible to parent class Chapter 4: Lists and the Collection Interface
Linked List: Insert • Suppose we want to insert “Bob” after “Harry” • First, set next of Bob to next of Harry • Second, change Harry’s next to point to Bob • Note that the order matters! Chapter 4: Lists and the Collection Interface
Linked List: Remove • Suppose we want to remove “Dick” from the list • First, note that Tom comes before Dick in list • Second, change next of Tom to next of Dick • Note that we must know predecessor of Dick Chapter 4: Lists and the Collection Interface
Traversing a Linked List • A fairly simple process: • Set nodeRef to reference of first node (head) • whilenodeRef is not null • do something with node referenced by nodeRef • Set nodeRef to nodeRef.next • At end of list, nodeRef = nodeRef.next; • Gives null, which is just fine • If you then execute this statement again, what happens? • The dreaded NullPointerException • You have fallen off the end of the linked list! Chapter 4: Lists and the Collection Interface
Circular Linked List • No beginning and no end • Kinda like trying to graduate from SJSU… • How to create a circular linked list? • Set next of last element to point to first element • Advantage(s)? • Cannot fall off the end of the list • Disadvantage(s)? • Possible infinite loop Chapter 4: Lists and the Collection Interface
Double-Linked Lists • Limitations of a single-linked list include: • Insertion at the front of the list is O(1). • Insertion at other positions is O(n) where n is the size of the list. • Can insert a node only after a referenced node • Can remove a node only if we have a reference to its predecessor node • Can traverse the list only in the forward direction • These limitations are eliminated by adding a reference in each node to the previous node: double-linked list Chapter 4: Lists and the Collection Interface
Double-Linked List: Example Chapter 4: Lists and the Collection Interface
Double-Linked List: Insert • We want to insert Sharon between Harry and Sam • Set Sharon’s next to Sam • Set Sharon’s prev to Harry • Set next of Harry to Sharon • Set prev of Sam to Sharon Chapter 4: Lists and the Collection Interface
Double-Linked List: Insert Chapter 4: Lists and the Collection Interface
Double-Linked List: Insert Chapter 4: Lists and the Collection Interface
Double-Linked List: Insert (Again) • We want to insert Sharon into list before Sam… • …only using references to Sam • Set sharon.next to sam • Set sharon.prev to sam.prev • Set sam.prev.next to sharon • Set sam.prev to sharon • Note that the order matters! • Must use sam.prev before changing it Chapter 4: Lists and the Collection Interface
Double-Linked List: Insert (Again) Chapter 4: Lists and the Collection Interface
Double-Linked List: Insert (Again) Chapter 4: Lists and the Collection Interface
Double-Linked List: Remove • Suppose we want to remove Harry • Where Harry is after Dick and before Sharon • Set dick.next to sharon • Set sharon.prev to dick Chapter 4: Lists and the Collection Interface