Chapter Objectives  The List interface  Implement lists based on arrays  Learn about List applications CS340 1.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Chapter 24 Lists, Stacks, and Queues
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
ITEC200 Week04 Lists and the Collection Interface.
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
Double-Linked Lists and Circular Lists
Section 2.5 Single-Linked Lists. A linked list is useful for inserting and removing at arbitrary locations The ArrayList is limited because its add and.
Lists and the Collections Framework
CHAPTER 4 Queues. Queue  The queue, like the stack, is a widely used data structure  A queue differs from a stack in one important way  A stack is.
CHAPTER 4 Queues MIDTERM THURSDAY, OCTOBER 17 IN LAB.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
Lists and the Collections Framework
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L11 (Chapter 20) Lists, Stacks,
1 Java intro Part 3. 2 Arrays in Java Store fixed number of values of a given type Arrays are objects –have attributes –must be constructed Array declaration:
Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Alice in Action with Java
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 26 Implementing Lists, Stacks,
List Interface CS java.util.List Interface and its Implementers CS340 2.
Chapter 101 Dynamic Data Structures and Generics Chapter 10.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Arrays And ArrayLists - S. Kelly-Bootle
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CHAPTER 2 Lists and the Collections Framework. Chapter Objectives  The List interface  Writing an array-based implementation of List  Linked list data.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Lists and the Collection Interface Review inheritance & collections.
GENERICS. Generics  Classes and methods can have a type parameter (actually, more than one).  The type parameter can be any reference (class) type.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
Chapter Objectives  Learn how to represent a waiting line (queue)  Become proficient using the methods in the Queue  Understand how to implement the.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Lists and the Collection Interface Chapter 4. 2 The List Interface and ArrayList Class So far, all we have is an array for storing a collection of elements.
Wrapper Classes and ArrayList Mrs. C. Furman 9/15/2008.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Lecture Objectives  Linked list data structures:  Singly-linked (cont.)  Doubly-linked  Circular  Implementing the List interface as a linked list.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
List Interface and Linked List Mrs. Furman March 25, 2010.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
CHAPTER 2 Lists and the Collections Framework. Chapter Objectives  The List interface  Writing an array-based implementation of List  Linked list data.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
1 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Jung Soo (Sue) Lim Cal State LA.
Single-Linked Lists.
Lists and the Collections Framework
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
COMP 121 Week 9: ArrayList.
Chapter 17 Object-Oriented Data Structures
Lists and the Collections Framework
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Dynamic Data Structures and Generics
Object Oriented Programming in java
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
Lists and the Collection Interface
Single-Linked Lists Section 2.5.
ArrayLists 22-Feb-19.
Chapter 4 Queues.
Programming II (CS300) Chapter 07: Linked Lists
Presentation transcript:

Chapter Objectives  The List interface  Implement lists based on arrays  Learn about List applications CS340 1

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

List Interface and ArrayList Class CS340 3

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

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

java.util.List Interface and its Implementers CS340 6

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

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

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

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

ArrayList Class (cont.)  No subscript specified: myList.add(“Star Wars"); CS The Lord of the Rings The HobbitInceptionThe MatrixThe Pirates of the Caribbean myList = [0][1][2][3] [4] Star Wars [5]

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

ArrayList Class (cont.)  You may also replace an element: myList.set(2, “Dune"); CS 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 =

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); CS The Lord of the Rings InceptionDuneThe Pirates of the Caribbean [0][1][2][3] [4] Star Wars myList =

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 CS The Lord of the Rings InceptionDuneThe Pirates of the Caribbean [0][1][2][3] [4] Star Wars myList =

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

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

Why Use Generic Collections?  Better type-checking: catch more errors, catch them earlier  Documents intent  Avoids the need to downcast from Object CS340 18

Specification of the ArrayList Class CS340 19

Applications of ArrayList 20 CS340

Phone Directory Application public class Book{ String title; String author; } Create a class for books stored in the library CS340 21

Phone Directory Application (cont.) public class Book{ String title; String author; } private ArrayList theLibrary = new ArrayList (); Create the library CS340 22

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

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

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

Implementation of an ArrayList Class CS340 26

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

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

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

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

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

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

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

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

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

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

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); } CS The reason for doubling is to spread out the cost of copying; we discuss this further in the next section

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

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

Single-Linked Lists CS340 40

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

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

List Nodes for Single-Linked Lists private static class Node { private E data; private Node next; /** Creates a new node with a null next 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

List Nodes for Single-Linked Lists (cont.) /** Creates a new node that references another dataItem The data nodeRef The node referenced by new node */ private Node(E dataItem, Node nodeRef) { data = dataItem; next = nodeRef; } CS340 44

Connecting Nodes CS340 45

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

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

SLList : An Example List head = SLList next = data = "Tom" Node next = data = “Helen" Node CS340 48

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

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

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

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

Implementing removeAfter(Node node) CS head = SLList next = data = "Tom" Node next = data = “Helen" Node next = data = "Ann" Node temp The Node parameter

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

Implementing SLList.removeFirst() CS head = SLList next = data = "Tom" Node next = data = “Helen" Node temp

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

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

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

Completing the SingleLinkedList Class CS340 59

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

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

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

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

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