Download presentation
Presentation is loading. Please wait.
Published byAron Rose Modified over 9 years ago
1
Chapter Objectives The List interface Implement lists based on arrays Learn about List applications CS340 1
2
Introduction A list is a collection of elements, each with a position or index Iterators facilitate sequential access to lists Classes ArrayList Vector LinkedList are subclasses of abstract class AbstractList and implement the List interface CS340 2
3
List Interface and ArrayList Class CS340 3
4
List Interface and ArrayList Class An array is an indexed structure elements may be accessed in any order using subscript values elements can be accessed in sequence using a loop that increments the subscript With the Java Array object, you cannot increase or decrease its length add an element at a specified position without shifting elements remove an element at a specified position and keep the elements contiguous without shifting CS340 4
5
List Interface and ArrayList Class (cont.) Java provides a List interface as part of its API java.util Classes that implement the List interface: provide indexed data structure functions offer many more operations: Obtain an element at a specified position Replace an element at a specified position Find a specified target value Add an element at either end Remove an element from either end Insert or remove an element at any position Traverse the list structure without managing a subscript CS340 5
6
java.util.List Interface and its Implementers CS340 6
7
List Interface and ArrayList Class 7 List interface cannot store primitive types Classes must store values as objects We need to use object wrappers, ex. Integer, Double CS340
8
ArrayList Class The simplest class that implements the List interface An improvement over an array object Use when: you need to add new elements to the end of a list you need to access elements quickly in any order CS340 8
9
ArrayList Class (cont.) To declare a List “object” whose elements will reference String objects: List myList = new ArrayList (); To add strings to the list, myList.add(“The Lord of the Rings"); myList.add(“The Hobbit"); myList.add(“The Matrix"); myList.add(“The Pirates of the Caribbean"); CS340 9
10
ArrayList Class (cont.) Adding an element with subscript 2: myList.add(2, “Inception"); 10 The Lord of the Rings The HobbitThe MatrixThe Pirates of the Caribbean The Lord of the Rings The HobbitInceptionThe MatrixThe Pirates of the Caribbean [0][1][2][3] myList = [0][1][2][3] [4] CS340
11
ArrayList Class (cont.) No subscript specified: myList.add(“Star Wars"); CS340 11 The Lord of the Rings The HobbitInceptionThe MatrixThe Pirates of the Caribbean myList = [0][1][2][3] [4] Star Wars [5]
12
ArrayList Class (cont.) Removing an element: myList.remove(1); 12 The Lord of the Rings The HobbitInceptionThe MatrixThe Pirates of the Carribean [0][1][2][3] [4] Star Wars [5] myList = The Lord of the Rings InceptionThe MatrixThe Pirates of the Caribbean [0][1][2][3] [4] Star Wars myList = CS340
13
ArrayList Class (cont.) You may also replace an element: myList.set(2, “Dune"); CS340 13 The Lord of the Rings InceptionThe MatrixThe Pirates of the Caribbean [0][1][2][3] [4] Star Wars myList = The Lord of the Rings InceptionDuneThe Pirates of the Caribbean [0][1][2][3] [4] Star Wars myList =
14
ArrayList Class (cont.) You cannot access an element using a bracket index as you can with arrays ( array[1] ) Instead, you must use the get() method: String movie = myList.get(3); CS340 14 The Lord of the Rings InceptionDuneThe Pirates of the Caribbean [0][1][2][3] [4] Star Wars myList =
15
ArrayList Class (cont.) You can also search an ArrayList : myList.indexOf(“Inception"); This returns 1 while myList.indexOf(“Green Lantern"); returns -1 which indicates an unsuccessful search CS340 15 The Lord of the Rings InceptionDuneThe Pirates of the Caribbean [0][1][2][3] [4] Star Wars myList =
16
Generic Collections The statement List myList = new ArrayList (); uses generic collections or generics Only references of type String can be stored in the list String in this statement is called a type parameter Sets the data type of all objects stored in a collection CS340 16
17
Generic Collections (cont.) The general declaration for generic collection is CollectionClassName variable = new CollectionClassName (); The indicates a type parameter However, primitive types will be autoboxed: ArrayList myList = new ArrayList (); myList.add(new Integer(3)); // ok myList.add(3); // also ok! 3 is automatically wrapped in an Integer object myList.add(new String("Hello")); // generates a type incompatability error CS340 17
18
Why Use Generic Collections? Better type-checking: catch more errors, catch them earlier Documents intent Avoids the need to downcast from Object CS340 18
19
Specification of the ArrayList Class CS340 19
20
Applications of ArrayList 20 CS340
21
Phone Directory Application public class Book{ String title; String author; } Create a class for books stored in the library CS340 21
22
Phone Directory Application (cont.) public class Book{ String title; String author; } private ArrayList theLibrary = new ArrayList (); Create the library CS340 22
23
Phone Directory Application (cont.) public class Book{ String title; String author; } private ArrayList theLibrary = new ArrayList (); theLibrary.add(new Book(“Harry Potter", "Joanne Rowling")); Add a DirectoryEntry object CS340 23
24
Phone Directory Application (cont.) public class Book{ String title; String author; } private ArrayList theLibrary = new ArrayList (); theLibrary.add(new Book(“Harry Potter", "Joanne Rowling")); int index = theLibrary.indexOf(new Book(aName, "")); Method indexOf searches theLibrary by applying the equals method for class Book CS340 24
25
Phone Directory Application (cont.) public class Book{ String title; String author; } private ArrayList theLibrary = new ArrayList (); theLibrary.add(new Book(“Harry Potter", "Joanne Rowling")); int index = theLibrary.indexOf(new Book(aName, "")); if (index != -1) dE = theLibrary.get(index); else dE = null; 25 CS340
26
Implementation of an ArrayList Class CS340 26
27
Implementing an ArrayList Class CS340ArrayList : a simple implementation of ArrayList How many elements the array can take: capacity Number of data items in the array: size CS340 27
28
CS340ArrayList Fields import java.util.*; public class CS340ArrayList { /** The default initial capacity */ private static final int INITIAL_CAPACITY = 10; /** The underlying data array */ private E[] theData; /** The current size */ private int size = 0; /** The current capacity */ private int capacity = 0; } 28
29
CS340ArrayList Constructor public CS340ArrayList () { capacity = INITIAL_CAPACITY; theData = (E[]) new Object[capacity]; } Allocates storage for an array of type Object and then casts the array object to type E[] CS340 29
30
Implementing ArrayList.add(E) We will implement two add methods Append at the end of the list Insert an item at a specified position CS340 30
31
Implementing ArrayList.add(E) (cont.) If size < capacity, then to append a new item 1. insert the new item at the position indicated by size 2. increment size 3. return true for successful insertion 31 CS340
32
Implementing ArrayList.add(int index,E anEntry) To insert into position index: the values at the insertion point are shifted over to make room, beginning at the end of the array and proceeding in the indicated order CS340 32
33
Implementing ArrayList.add(index,E) public void add (int index, E anEntry) { // check bounds if (index size) { throw new ArrayIndexOutOfBoundsException(index); } // Make sure there is room if (size >= capacity) { reallocate(); } // shift data for (int i = size; i > index; i--) { theData[i] = theData[i-1]; } // insert item theData[index] = anEntry; size++; } CS340 33
34
set and get Methods public E get (int index) { if (index = size) { throw new ArrayIndexOutOfBoundsException(index); } return theData[index]; } public E set (int index, E newValue) { if (index = size) { throw new ArrayIndexOutOfBoundsException(index); } E oldValue = theData[index]; theData[index] = newValue; return oldValue; } CS340 34
35
remove Method Move forward items to close the gap Begin with the item closest to the removed element and proceed in the indicated order CS340 35
36
remove Method (cont.) public E remove (int index) { if (index = size) { throw new ArrayIndexOutOfBoundsException(index); } E returnValue = theData[index]; for (int i = index + 1; i < size; i++) { theData[i-1] = theData[i]; } size--; return returnValue; } CS340 36
37
reallocate Method Create a new array that is twice the size of the current array Copy the contents of the new array private void reallocate () { capacity *= 2; theData = Arrays.copyOf(theData, capacity); } CS340 37 The reason for doubling is to spread out the cost of copying; we discuss this further in the next section
38
CS340ArrayList as a Collection of Objects Remove the parameter type from the class heading, Replace each reference to data type E by Object The underlying data array becomes private Object[] theData; CS340 38
39
Vector Class The Java API java.util contains two very similar classes, Vector and ArrayList New applications normally use ArrayList rather than Vector ArrayList is generally more efficient Vector class is synchronized Multiple threads can access a Vector object without conflict CS340 39
40
Single-Linked Lists CS340 40
41
Single-Linked Lists Useful for inserting removing at arbitrary locations ArrayList : add and remove methods operate in linear O(n) time A linked list can add and remove elements at a known location in O(1) time CS340 41
42
A List Node A node can contain: a data item one or more links A link is a reference to a list node In our list the node contains: a data field named data of type E a reference to the next node, named next CS340 42
43
List Nodes for Single-Linked Lists private static class Node { private E data; private Node next; /** Creates a new node with a null next field @param dataItem The data stored */ private Node(E dataItem) { data = dataItem; next = null; } // continued on next page static indicates that the Node class will not reference its outer class Static inner classes are also called nested classes CS340 43
44
List Nodes for Single-Linked Lists (cont.) /** Creates a new node that references another node @param dataItem The data stored @param nodeRef The node referenced by new node */ private Node(E dataItem, Node nodeRef) { data = dataItem; next = nodeRef; } CS340 44
45
Connecting Nodes CS340 45
46
Connecting Nodes (cont.) Node tom = new Node ("Tom"); Node dick = new Node ("Dick"); Node harry = new Node ("Harry"); Node sam = new Node ("Sam"); tom.next = dick; dick.next = harry; harry.next = sam; CS340 46
47
A Single-Linked List Class A SingleLinkedList object has a data field head, which references the first list node public class SingleLinkedList { private Node head = null; private int size = 0;... } CS340 47
48
SLList : An Example List head = SLList next = data = "Tom" Node next = data = “Helen" Node CS340 48
49
Implementing SLList.addFirst(E item) head = SLList next = data = "Tom" Node next = data = “Helen" Node next = data = "Ann" Node The element added to the list CS340 49
50
Implementing SLList.addFirst(E item) (cont.) private void addFirst (E item) { Node temp = new Node (item, head); head = temp; size++; } or, more simply... private void addFirst (E item) { head = new Node (item, head); size++; } This works even if head is null CS340 50
51
Implementing addAfter(Node node, E item) head = SLList next = data = "Tom" Node next = data = “Helen" Node next = data = "Ann" Node The element added to the list CS340 51
52
Implementing addAfter(Node node, E item) (cont.) private void addAfter (Node node, E item) { Node temp = new Node (item, node.next); node.next = temp; size++; } or, more simply... private void addAfter (Node node, E item) { node.next = new Node (item, node.next); size++; } We declare this method private since it should not be called from outside the class CS340 52
53
Implementing removeAfter(Node node) CS340 53 head = SLList next = data = "Tom" Node next = data = “Helen" Node next = data = "Ann" Node temp The Node parameter
54
Implementing removeAfter(Node node) (cont.) private E removeAfter (Node node) { Node temp = node.next; if (temp != null) { node.next = temp.next; size--; return temp.data; } else { return null; } CS340 54
55
Implementing SLList.removeFirst() CS340 55 head = SLList next = data = "Tom" Node next = data = “Helen" Node temp
56
Implementing SLList.removeFirst() (cont.) private E removeFirst () { Node temp = head; if (head != null) { head = head.next; } if (temp != null) { size--; return temp.data } else { return null; } CS340 56
57
Traversing a Single-Linked List head = SLList next = data = "Tom" Node next = data = “Helen" Node next = data = "Ann" null Node nodeRef Do something with nodeRef CS340 57
58
Traversing a Single-Linked List (cont.) toString() can be implemented with a traversal: public String toString() { Node nodeRef = head; StringBuilder result = new StringBuilder(); while (nodeRef != null) { result.append(nodeRef.data); if (nodeRef.next != null) { result.append(" ==> "); } nodeRef = nodeRef.next; } return result.toString(); } CS340 58
59
Completing the SingleLinkedList Class CS340 59
60
SLList.getNode(int) Additional helper method: private Node getNode(int index) { Node node = head; for (int i=0; i<index && node != null; i++) { node = node.next; } return node; } CS340 60
61
public E get(int index) public E get (int index) { if (index = size) { throw new IndexOutOfBoundsException(Integer.toString(index)); } Node node = getNode(index); return node.data; } CS340 61
62
public E set(int index, E newValue) public E set (int index, E newValue) { if (index = size) { throw new IndexOutOfBoundsException(Integer.toString(ind ex)); } Node node = getNode(index); E result = node.data; node.data = newValue; return result; } CS340 62
63
public void add(int index, E item) public void add (int index, E item) { if (index size) { throw new IndexOutOfBoundsException(Integer.toString(index)); } if (index == 0) { addFirst(item); } else { Node node = getNode(index-1); addAfter(node, item); } 63
64
public boolean add(E item) To add an item to the end of the list public boolean add (E item) { add(size, item); return true; } CS340 64
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.