Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations

Presentation on theme: "Sprint 2010CS 2251 Lists and the Collection Interface Chapter 2."— Presentation transcript:

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

2 Sprint 2010CS 2252 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

3 Sprint 2010CS 2253 List An expandable collection of elements –each element has a position (index) We'll see two kinds of lists in this chapter –ArrayList –LinkedList

4 Sprint 2010CS 2254 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

5 Sprint 2010CS 2255 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.

6 Sprint 2010CS 2256 Java List Classes

7 Sprint 2010CS 2257 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

8 Sprint 2010CS 2258 Using ArrayList

9 Sprint 2010CS 2259 Using ArrayList

10 Sprint 2010CS 22510 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 myList = new ArrayList (); 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.

11 Sprint 2010CS 22511 Specification of the ArrayList Class

12 Sprint 2010CS 22512 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

13 Sprint 2010CS 22513 Creating and Populating an ArrayList ArrayList someInts = new ArrayList ; int nums = {5, 7, 2, 15}; for (int i=0; i<nums.length; i++) someInts.add( nums[i]); ArrayList theDirectory = new ArrayList (); theDirectory.add( new Entry( "Jane Smith", "555-549-1234");

14 Sprint 2010CS 22514 Traversing an ArrayList int sum = 0; for (int i=0; i<someInts.size(); i++) sum +=someInts.get(i); System.out.println( "sum is " + sum);

15 Sprint 2010CS 22515 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

16 Sprint 2010CS 22516 KWArrayList class public class KWArrayList { private E[] theData; private int size, capacity; public KWArrayList() { capacity = 10; theData = new (E[])Object[capacity]; }

17 Sprint 2010CS 22517 ArrayList Operations add insert remove

18 Sprint 2010CS 22518 Non-generic KWArrayList public class KWArrayList { private Object[] theData; private int size, capacity; public KWArrayList() { capacity = 10; theData = new Object[capacity]; }

19 Sprint 2010CS 22519 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

20 Sprint 2010CS 22520 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

21 Sprint 2010CS 22521 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

22 Sprint 2010CS 22522 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

23 Sprint 2010CS 22523 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)

24 Sprint 2010CS 22524 Example 4 (cont.) We can reduce the expression in parentheses to: –n x (n – 1) / 2 So, T(n) = 1.5n 2 – 1.5n This polynomial is zero when n is 1. For values greater than 1, 1.5n 2 is always greater than 1.5n 2 – 1.5n Therefore, we can use 1 for n 0 and 1.5 for c to conclude that T(n) is O(n 2 )

25 Sprint 2010CS 22525 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

26 Sprint 2010CS 22526 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 n 0 and c such that for all n>n 0, cf(n) >= T(n) f(n) provides an upper bound to the time the algorithm takes to run

27 Sprint 2010CS 22527 Comparing Performance

28 Sprint 2010CS 22528 Sample Numbers O(f(n))f(50)f(100) f(100)/f(5 0) O(1)111 O(log n)5.646.641.18 O(n)501002 O(n log n) 2826642.35 O(n 2 )2500100004 O(n 3 )1250010000008 O2 n )1.13 x 10 15 1.27 x 10 30 1.13 x 10 15 O(n!)3 x 10 64 9.3 x 10 157 3.1 x 10 93

29 Sprint 2010CS 22529 Performance of KWArrayList MethodEfficiency addO(1) getO(1) insertO(N) removeO(N)

30 Sprint 2010CS 22530 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

31 Sprint 2010CS 22531 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

32 Sprint 2010CS 22532 Build A Single-Linked List Node tom = new Node ("Tom"); Node dick = new Node ("Dick"); = dick; Node tom = new Node ("Harry"); =harry;

33 Sprint 2010CS 22533 Add to Single-Linked List Node bob = new Node ("Bob"); =; = bob;

34 Sprint 2010CS 22534 Remove from Single-Linked List =;

35 Sprint 2010CS 22535 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

36 Sprint 2010CS 22536 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?

37 Sprint 2010CS 22537 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)

38 Sprint 2010CS 22538 Double-Linked Lists

39 Sprint 2010CS 22539 Inserting into a Double-Linked List

40 Sprint 2010CS 22540 Inserting into a Double-Linked List

41 Sprint 2010CS 22541 Removing from a Double- Linked List

42 Sprint 2010CS 22542 Double-Linked List Class Similar to Single-Linked List with an extra data member for the end of the list

43 Sprint 2010CS 22543 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!)

44 Sprint 2010CS 22544 Circular Lists

45 Sprint 2010CS 22545 The LinkedList Class Part of the Java API Implements the List interface using a double-linked list

46 Sprint 2010CS 22546 List Traversal using get What is the efficiency of e for (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(n 2 ) behavior We ought to be able to traverse a list on O(n) time

47 Sprint 2010CS 22547 The Iterator 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

48 Sprint 2010CS 22548 The Iterator 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

49 Sprint 2010CS 22549 The Iterator Interface Get O(n) efficiency with while (iter.hasNext()) { E element =; i // process element e }

50 Sprint 2010CS 22550 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

51 Sprint 2010CS 22551 ListIterator ListIterator is an extension of the Iterator interface for overcoming the above limitations

52 Sprint 2010CS 22552 The ListIterator Interface

53 Sprint 2010CS 22553 The ListIterator Interface (continued)

54 Sprint 2010CS 22554 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

55 Sprint 2010CS 22555 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

56 Sprint 2010CS 22556 The Enhanced for Statement Java has a special for statement that can be used with collections d for (E element : list) // process element This type of loop uses the Iterator available in the list to traverse the elements of the list.

57 Sprint 2010CS 22557 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

58 Sprint 2010CS 22558 Implementation of a Double- Linked List

59 Sprint 2010CS 22559 Double-Linked List with Iterator

60 Sprint 2010CS 22560 Advancing the Iterator

61 KWLinkedList This is a doubly-linked list It implements ListIterator Most of the methods use a ListIterator to do their task

62 Sprint 2010CS 22562 Adding to an Empty Double- Linked List

63 Sprint 2010CS 22563 Adding to Front of a Double- Linked List

64 Sprint 2010CS 22564 Adding to End of a Double- Linked List

65 Sprint 2010CS 22565 Adding to Middle of a Double- Linked List

66 Sprint 2010CS 22566 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

67 Sprint 2010CS 22567 The Collection Hierarchy

68 Sprint 2010CS 22568 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

69 Sprint 2010CS 22569 Common Features of Collections

70 Sprint 2010CS 22570 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

71 Sprint 2010CS 22571 OrderedList Application

72 Sprint 2010CS 22572 Ordered List

73 Sprint 2010CS 22573 Ordered List Insertion

74 Sprint 2010CS 22574 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

75 Sprint 2010CS 22575 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

76 Sprint 2010CS 22576 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

77 Sprint 2010CS 22577 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

78 Sprint 2010CS 22578 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

79 Sprint 2010CS 22579 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

80 Sprint 2010CS 22580 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

81 Sprint 2010CS 22581 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

82 Sprint 2010CS 22582 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

83 Sprint 2010CS 22583 Developing the Test Data Test data should be specified during the analysis and design phases for the different levels of testing unit integration system

84 Sprint 2010CS 22584 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

85 Sprint 2010CS 22585 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

86 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

87 Sprint 2010CS 22587 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.

88 Sprint 2010CS 22588 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

89 Sprint 2010CS 22589 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

90 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

91 Sprint 2010CS 22591 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

92 JUnit Testing A Java framework for unit testing See Appendix D See tools.ppt

93 Iterator Integrity

94 Potential Iterator Pitfalls Null references a well-designed and implemented iterator should never return a null References to removed cells Using the regular remove method while there is an active iterator Using the iterator remove method when there are multiple active iterators

95 Approaches Do nothing and hope for the best Lock the collection so it can't change while an iterator is active This 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

96 Java Example ArrayList extends AbstractList code is available in /usr/local/java/src/java/util

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

Similar presentations

Ads by Google