Sprint 2010CS 2251 Lists and the Collection Interface Chapter 2.

96
Sprint 2010 CS 225 1 Lists and the Collection Interface Chapter 2
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    221
  • download

    2

Transcript of Sprint 2010CS 2251 Lists and the Collection Interface Chapter 2.

Sprint 2010 CS 225 1

Lists and the Collection Interface

Chapter 2

Sprint 2010 CS 225 2

Chapter Objectives

• Become familiar with the List interface• Study array-based implementation of List• Understand single, double and circularly linked lists• Understand the meaning of big-O notation for

algorithm analysis• Study single-linked list implementation of List• Understand the Iterator interface • Implement Iterator for a linked list• Understand testing strategies• Become familiar with the java Collections Framework

Sprint 2010 CS 225 3

List

• An expandable collection of elements– each element has a position (index)

• We'll see two kinds of lists in this chapter– ArrayList– LinkedList

Sprint 2010 CS 225 4

Arrays• An array is an indexed structure

– Random access - can select its elements in arbitrary order using a subscript value

• Elements may be accessed in sequence using a loop that increments the subscript

• 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

Sprint 2010 CS 225 5

The List Interface

• List interface operations:– 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.

Sprint 2010 CS 225 6

Java List Classes

Sprint 2010 CS 225 7

The ArrayList Class

• Simplest class that implements the List interface

• Improvement over an array object– How?

• 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

Sprint 2010 CS 225 8

Using ArrayList

Sprint 2010 CS 225 9

Using ArrayList

Sprint 2010 CS 225 10

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 a specific type• List<String> myList = new ArrayList<String>();

• specifies that myList is a List of String where• String is a type parameter which is analogous to

a method parameter. • Only references to objects of type String can be

stored in myList, and all items retrieved would be of type String.

Sprint 2010 CS 225 11

Specification of the ArrayList Class

Sprint 2010 CS 225 12

Advantages 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

Sprint 2010 CS 225 13

Creating and Populating an ArrayList

• ArrayList<Integer> someInts = new ArrayList<Integer>;

• int nums = {5, 7, 2, 15};• for (int i=0; i<nums.length; i++)• someInts.add( nums[i]);

• ArrayList<Entry> theDirectory = new ArrayList<Entry>();

• theDirectory.add( new Entry( "Jane Smith", "555-549-1234");

Sprint 2010 CS 225 14

Traversing an ArrayList

• int sum = 0;• for (int i=0; i<someInts.size(); i++)

• sum +=someInts.get(i);• System.out.println( "sum is " + sum);

Sprint 2010 CS 225 15

ArrayList Implementation

• KWArrayList: simple implementation of a ArrayList class– Physical size of array indicated by data

field capacity– Number of data items indicated by the data

field size

Sprint 2010 CS 225 16

KWArrayList class

• public class KWArrayList<E> {• private E[] theData;• private int size, capacity;

• public KWArrayList() {• capacity = 10;• theData = new • (E[])Object[capacity];• }• }

Sprint 2010 CS 225 17

ArrayList Operations

add

insert

remove

Sprint 2010 CS 225 18

Non-generic KWArrayList

• public class KWArrayList {• private Object[] theData;• private int size, capacity;

• public KWArrayList() {• capacity = 10;• theData = new • Object[capacity];• }• }

Sprint 2010 CS 225 19

Efficiency of Algorithms

• For programs that manage large collections of data, we need to be concerned with how efficient the program is.

• Measuring the time it takes for a particular part of the program to run is not easy to do accurately.

• We can characterize a program by how the execution time or memory requirements increase as a function of increasing input size– Big-O notation

• A simple way to determine the big-O of an algorithm or program is to look at the loops and to see whether the loops are nested

Sprint 2010 CS 225 20

Example 1

• How many times does the body of this loop execute?

• public static int search( int [] x, int target) {

– for (int i=0; i<x.length; i++)• if (x[i] == target)• return i;• return -1;w }

On average, x.length / 2

Sprint 2010 CS 225 21

Example 2

• How many times does the body of this loop execute?

e public static boolean areDifferent( int [] x, int [] y) {

• for (int i=0; i<x.length; i++)– if (search( y, x[i]) != -1)• return false;• return true;g }

On average, x.length * y.length

Sprint 2010 CS 225 22

Example 3

• How many times does the body of this loop execute?

g public static boolean areUnique( int [] x) {

• for (int i=0; i<x.length; i++)• for (int j=0; j<x.length; i++)– if (i!=j && x[i] == x[j])• return false;e return true;• }

On average, x.length * x.length

Sprint 2010 CS 225 23

Example 4

• Consider:

• First time through outer loop, inner loop is executed n-1 times; next time n-2, and the last time once.

• So we have – T(n) = 3(n – 1) + 3(n – 2) + … + 3 or– T(n) = 3(n – 1 + n – 2 + … + 1)

Sprint 2010 CS 225 24

Example 4 (cont.)

• We can reduce the expression in parentheses to:– n x (n – 1) / 2

• So, T(n) = 1.5n2 – 1.5n • This polynomial is zero when n is 1. For

values greater than 1, 1.5n2 is always greater than 1.5n2 – 1.5n

• Therefore, we can use 1 for n0 and 1.5 for c to conclude that T(n) is O(n2)

Sprint 2010 CS 225 25

Big-O Notation

• We generally specify the efficiency of an algorithm by giving an "order-of-magnitude" estimate of how the time taken to run it depends on the size of the input (n)– Example 1: O(x.length)– Example 2: O(x.length * y.length)– Example 2: O(x.length 2)

• We call this Big-O notation

Sprint 2010 CS 225 26

Big-O

• Asume T(n) is a function that counts the number of operations in an algorithm as a function of n

• The algorithm is O(f(n)) if there exist two positive (>0) constants n0 and c such that for all n>n0, cf(n) >= T(n)

• f(n) provides an upper bound to the time the algorithm takes to run

Sprint 2010 CS 225 27

Comparing Performance

Sprint 2010 CS 225 28

Sample Numbers

O(f(n)) f(50) f(100) f(100)/f(50)

O(1) 1 1 1O(log n) 5.64 6.64 1.18O(n) 50 100 2O(n log n) 282 664 2.35

O(n2) 2500 10000 4O(n3) 12500 1000000 8

O2n) 1.13 x 1015 1.27 x 1030

1.13 x 1015

O(n!) 3 x 1064 9.3 x 10157 3.1 x 1093

Sprint 2010 CS 225 29

Performance of KWArrayList

Method Efficiency

add O(1)

get O(1)

insert O(N)

remove O(N)

Sprint 2010 CS 225 30

Improving List Performance

• The ArrayList: add and remove methods operate in linear time because they require a loop to shift elements in the underlying 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, and optionally previous, node

Sprint 2010 CS 225 31

A List Node

• A node contains a data item and one or more links– A link is a reference to another node

• A node is generally defined inside of another class, making it an inner class

• The details of a node should be kept private

• See KWLinkedList

Sprint 2010 CS 225 32

Build A Single-Linked ListNode<String> tom = new Node<String>("Tom");Node<String> dick = new Node<String>("Dick");tom.next = dick;Node<String> tom = new Node<String>("Harry");dick.next =harry;

Sprint 2010 CS 225 33

Add to Single-Linked List

Node<String> bob = new Node<String>("Bob");bob.next = harry.next; harry.next = bob;

Sprint 2010 CS 225 34

Remove from Single-Linked List

tom.next = dick.next;

Sprint 2010 CS 225 35

Traversing a Single-Linked List

• Set nodeRef to first Node

• while NodeRef is not null• process data in node referenced by

nodeRef• set nodeRef to nodeRef.next

Sprint 2010 CS 225 36

Other Methods

• To implement the List interface, we need to add methods– get data at a particular index– set data at a particular index– add at a specified index

• Provide a helper method getNode to find the node at a particular index– What is the efficiency of this method?

Sprint 2010 CS 225 37

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

• Above limitations removed by adding a reference in each node to the previous node (double-linked list)

Sprint 2010 CS 225 38

Double-Linked Lists

Sprint 2010 CS 225 39

Inserting into a Double-Linked List

Sprint 2010 CS 225 40

Inserting into a Double-Linked List

Sprint 2010 CS 225 41

Removing from a Double-Linked List

Sprint 2010 CS 225 42

Double-Linked List Class

• Similar to Single-Linked List with an extra data member for the end of the list

Sprint 2010 CS 225 43

Circular Lists

• Circular-linked list: link the last node of a double-linked list to the first node and the first to the last

• Advantage: can traverse in forward or reverse direction even after you have passed the last or first node– Can visit all the list elements from any starting

point

• Can never fall off the end of a list• Disadvantage: How do you know when to

quit? (infinite loop!)

Sprint 2010 CS 225 44

Circular Lists

Sprint 2010 CS 225 45

The LinkedList<E> Class

• Part of the Java API

• Implements the List<E> interface using a double-linked list

Sprint 2010 CS 225 46

List Traversal using get

• What is the efficiency of efor (int index=0; index<aList.size; index++) {

• E element = aList.get( index);

• // process element• }• get operates in O(n) time for a linked list• Calling get n times results in O(n2) behavior• We ought to be able to traverse a list on O(n) time

Sprint 2010 CS 225 47

The Iterator<E> Interface

• The interface Iterator is defined as part of API package java.util

• The List interface declares the method iterator, which returns an Iterator object that will iterate over the elements of that list

• An Iterator does not refer to or point to a particular node at any given time but points between nodes

Sprint 2010 CS 225 48

The Iterator<E> Interface

• An Iterator allows us to keep track of where we are in a list

• List interface has a method called iterator() which returns an Iterator object

Sprint 2010 CS 225 49

The Iterator<E> Interface

• Get O(n) efficiency with• while (iter.hasNext()) {• E element = iter.next();i // process elemente}

Sprint 2010 CS 225 50

Improving on Iterator

• Iterator limitations• Can only traverse the List in the forward

direction• Provides only a remove method• Must advance an iterator using your own loop if

starting position is not at the beginning of the list

Sprint 2010 CS 225 51

ListIterator

• ListIterator<E> is an extension of the Iterator<E> interface for overcoming the above limitations

Sprint 2010 CS 225 52

The ListIterator<E> Interface

Sprint 2010 CS 225 53

The ListIterator<E> Interface (continued)

Sprint 2010 CS 225 54

Iterator vs. ListIterator

• ListIterator is a subinterface of Iterator; classes that implement ListIterator provide all the capabilities of both

• Iterator interface requires fewer methods and can be used to iterate over more general data structures but only in one direction

• Iterator is required by the Collection interface, whereas the ListIterator is required only by the List interface

Sprint 2010 CS 225 55

Combining ListIterator and Indexes

• ListIterator has the methods nextIndex and previousIndex, which return the index values associated with the items that would be returned by a call to the next or previous methods

• The LinkedList class has the method listIterator(int index) – Returns a ListIterator whose next call to

next will return the item at position index

Sprint 2010 CS 225 56

The Enhanced for Statement

• Java has a special for statement that can be used with collections

dfor (E element : list)• // process element• This type of loop uses the Iterator

available in the list to traverse the elements of the list.

Sprint 2010 CS 225 57

The Iterable Interface

• This interface requires only that a class that implements it provide an iterator method

• The Collection interface extends the Iterable interface, so all classes that implement the List interface (a subinterface of Collection) must provide an iterator method

Sprint 2010 CS 225 58

Implementation of a Double-Linked List

Sprint 2010 CS 225 59

Double-Linked List with Iterator

Sprint 2010 CS 225 60

Advancing the Iterator

KWLinkedList

• This is a doubly-linked list• It implements ListIterator• Most of the methods use a ListIterator

to do their task

Sprint 2010 CS 225 62

Adding to an Empty Double-Linked List

Sprint 2010 CS 225 63

Adding to Front of a Double-Linked List

Sprint 2010 CS 225 64

Adding to End of a Double-Linked List

Sprint 2010 CS 225 65

Adding to Middle of a Double-Linked List

Sprint 2010 CS 225 66

The Collection Hierarchy

• Both the ArrayList and LinkedList represent a collection of objects that can be referenced by means of an index

• The Collection interface specifies a subset of the methods specified in the List interface

Sprint 2010 CS 225 67

The Collection Hierarchy

Sprint 2010 CS 225 68

Common Features of Collections

• Collection interface specifies a set of common methods

• Fundamental features include:– Collections grow as needed– Collections hold references to objects– Collections have at least two constructors

Sprint 2010 CS 225 69

Common Features of Collections

Sprint 2010 CS 225 70

LinkedList Application

• Case study that uses the Java LinkedList class to solve a common problem: maintaining an ordered list

• The list has-a LinkedList inside it• An example of aggregation

• The list operations are delegated to the LinkedList

Sprint 2010 CS 225 71

OrderedList Application

Sprint 2010 CS 225 72

Ordered List

Sprint 2010 CS 225 73

Ordered List Insertion

Sprint 2010 CS 225 74

Testing Programs

• There is no guarantee that a program that is syntax and run-time error free will also be void of logic errors

• Testing is the process of running a program under controlled conditions and verifying the results• Purpose is to detect program defects after all

syntax errors have been removed and the program compiles

• No amount of testing can guarantee the absence of defects in complex programs

Sprint 2010 CS 225 75

Levels of Testing

• Unit Testing: test the smallest part of the code that is feasible

• Integration Testing: test interactions between units (classes)

• System Testing: test the program in the context in which it will be used

• Acceptance Testing: demonstrate that the program meets the specification

Sprint 2010 CS 225 76

White- vs. Black-box Testing

• In black-box testing, we are concerned with the relationship between the unit inputs and outputs

• In white-box testing, we are concerned with exercising alternative paths through the code

• Try to exercise as many different paths through the code as possible

• statement coverage• branch coverage

Sprint 2010 CS 225 77

Sources of Logic Errors

• Most logic errors arise during the design phase and are the result of an incorrect algorithm• Best Case: a logic error that occurs in a part of the

program that always executes• Worst Case: a logic error is one that occurs in an

obscure (infrequently executed) part of the code

• Logic errors may also result from typographical errors that do not cause syntax or run-time errors

Sprint 2010 CS 225 78

Structured Walkthroughs

• One form of testing is hand-tracing the algorithm before implementing

• Structured walkthrough: designer must explain the algorithm to other team members and simulate its execution with other team members looking on

Sprint 2010 CS 225 79

Types of Testing

• Unit testing: checking the smallest testable piece of the software (a method or class)

• Integration testing: testing the interactions among units

• System testing: testing the program in context• Acceptance testing: system testing designed

to show that the program meets its functional requirements

Sprint 2010 CS 225 80

Preparations for Testing

• A test plan should be developed early in the design phase– Aspects of a test plan include deciding how the software will

be tested, when the tests will occur, who will do the testing, and what test data will be used

• If the test plan is developed early, testing can take place concurrently with the design and coding

• A good programmer practices defensive programming and includes code to detect unexpected or invalid data

Sprint 2010 CS 225 81

Testing Methods

• Most of the time, you will test program systems that contain collections of classes, each with several methods

1. Document the method parameters and class attributes as you write the code

2. Leave a trace of execution by displaying the method name as you enter it

3. Display values of all input parameters upon entry to a method

Sprint 2010 CS 225 82

Testing Methods (continued)

1. Display the values of any class attributes that are accessed by this method

2. Display the values of all method outputs after returning from a method

• Plan for testing as you write each module rather than after the fact• Include testing code in the class itself

• Allow the testing code to be disabled when testing is complete

Sprint 2010 CS 225 83

Developing the Test Data

• Test data should be specified during the analysis and design phases for the different levels of testing• unit• integration• system

Sprint 2010 CS 225 84

Black-box testing

• Tests the item based on its interfaces and functional requirements• There should be test data to check for all

expected inputs as well as unanticipated data

• Expected behavior should be specified in the test plan

Sprint 2010 CS 225 85

White-box testing

• Tests the software with the knowledge of its internal structure• Test data should ensure that all if statement

conditions will evaluate to both true and false• true and false cases for all if statements

• all case values plus some that aren't listed for a switch

• Make sure loops execute correctly for 0, 1 and more iterations

• check that loops always terminate

Testing Boundary Conditions

• For a loop that searches an array for a particular value• Search for first value• Search for last value• Search for value that is not in the array• Search for value in middle of array• Search for value that occurs multiple times• Search a 1-element array• Search an array with no elements

Sprint 2010 CS 225 87

Who does the Testing?

• Programmers are often blind to their own oversights

• Companies also have quality assurance organizations that verify that the testing process is performed correctly

• In extreme programming, programmers work in pairs where one writes the code and the other writes the tests

• Users effectively test the software too.

Sprint 2010 CS 225 88

When to test?

• Start testing as early as you can– don't wait until the coding is complete

• It may be difficult to test a method or class that interacts with other methods or classes

Sprint 2010 CS 225 89

Stubs

• A replacement for a method that has not yet been implemented or tested is called a stub

• A stub has the same header as the method it replaces, but its body only displays a message indicating that the stub was called – It may need a fixed return value

Preconditions and Postconditions

• Precondition: a statement of any assumptions or constraints on the method data before the method begins execution

• Postcondition: a statement that describes the result of executing a method

Sprint 2010 CS 225 91

Drivers

• A driver program declares any necessary object instances and variables, assigns values to any of the method’s inputs, calls the method, and displays the values of any outputs returned by the method

• You can put a main method in a class to serve as the test driver for that class’s methods

JUnit Testing

• A Java framework for unit testing• See Appendix D• See tools.ppt

Iterator Integrity

Potential Iterator Pitfalls

Null references a well-designed and implemented iterator

should never return a null

References to removed cellsUsing the regular remove method while there

is an active iteratorUsing the iterator remove method when

there are multiple active iterators

Approaches

Do nothing and hope for the best

Lock the collection so it can't change while an iterator is activeThis limits what you can do

What if you need multiple iterators

Design the iterator to "fail fast"This is the approach used in the java

Collections

Java Example

ArrayList extends AbstractList

code is available in /usr/local/java/src/java/util