550 likes | 571 Views
This course provides an in-depth understanding of the Java Collections Framework and its key methods. Learn how to store and access collections of elements using arrays and linked lists.
E N D
COM S 228 Collections and Iterators Instructor: Ying Cai Department of Computer Science Iowa State University yingcai@iastate.edu Office: Atanasoff 201
Java Collection Framework • Very often we need a way to store and access a collection of elements of the same type • A few factors to consider
Key methods of Collection<E> Key methods of Iterator<E>
Basic data structure Constructors
Array-based Implementation of FirstCollection Data size: the index of next available slot Iterator Cursor: the index of the item retrieved by next() • hasNext() • next() • remove() checkCapacity() • Advantages • Simple to implement • Disadvantages • A certain amount of memory is required for the array, even when the collection contains few elements • Removing an element requires all elements down to be shifted, making it an O(n) operations
Singly-Linked Lists data next
We can build a list like this Null-terminated singly-linked list
We can access any element by starting at head Mostly, we will use a loop:
We can build a list like this Null-terminated singly-linked list
Suppose we have this list Now we do this The result is This effectively removes the node containing c
Suppose we have this list What happens if we do this
Problems with Singly-Linked Lists • Cannot quickly access the predecessor, making it difficult to delete an element • Can only iterate in one direction
Iterator Cursor: the index of the item retrieved by next() FirstCollection • hasNext() • next() • remove() Array data Singly-Linked-List Doubly-Linked-List
The List Interface A list is a linearly ordered collection with random access to the elements. The List interface extends the Collection interface:
We will implement the List interface on top of the Existing class AbstractSequentialList.
newNode current
remove() needs to know which direction we’are coming from, AHEAD, BEHIND, or NONE. After it has been called, we have to set direction to NONE, so that it does not get called unless there’s another next() or previous().