Presentation on theme: "Lists Chapter 4 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-237045-X."— Presentation transcript:
1 ListsChapter 4Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X
2 Chapter Contents Specifications for the ADT List Using the ADT List Redefining the SpecificationsUsing the ADT ListUsing a List Is Like Using a Vending MachineJava Class Library: The Interface List
3 Specifications for the ADT List A list provides a way to organize dataFig A to-do list.
4 Specifications for the ADT List Operations on listsAdd new entry – at end, or anywhereRemove an itemRemove all itemsReplace an entryLook at any entryLook for an entry of a specific valueCount how many entriesCheck if list is empty, fullDisplay all the entries
5 Specifications for the ADT List To specify an ADT listDescribe its dataSpecify the operationsADT list must be considered in generalNot necessarily a list of stringsView specifications
6 Fig. 4-2 The effect of ADT list operations on an initially empty list ExampleFig The effect of ADT list operations on an initially empty list
7 Potential Problem Operations add, remove, replace, getEntry work OK when valid position givenremove, replace and getEntry not meaningful on empty listsA list could become full, what happens to add?
8 Possible Solutions Assume the invalid situations will not occur Ignore the invalid situationsMake reasonable assumptions, act in predictable wayReturn boolean value indicating success or failure of the operationThrow an exception
9 Redefining Specifications A first draft of an ADT specifications may ignore potential problemsSimplifies the first draftConcentrate on details after major portions of specifications writtenMakes the specifications completeAfter writing specifications, implementationsWrite Java statements to use the ADTChecks understanding, suitability of the specifications
10 Interface for ADT ListInterface View source codeNoteInterface has no data fields, constructorsMethods must be publicStrategy for add, remove, replace, getEntry is to have them return a valueUse of return of a reference in remove and getEntry
11 Using the ADT ListFig. 4-3 A list of numbers that identify runners in the order in which they finish a race
12 Using the ADT List Consider the scoring of a running race We wish to note the order in which the runners finishWe add each runner's (unique) number to the end of the listWhen done we display the whole listView sample program
13 A List is Like a Vending Machine Fig 4-4 A vending machine.
14 A List is Like a Vending Machine Observations about vending machinesCan perform only tasks shown on interfaceMust understand the tasksCannot see inside the machineCan use the machine even though don’t know what happens insideIf inside of machine replaced with new improved versionInterface remains unchangedCustomer uses machine in same way as before
15 A List is Like a Vending Machine Observations about clients and List ADTClient can perform only operations from the ADT ListClient must adhere to specificationsClient cannot access data without an ADT operationClient can use the list – even though unable to access entries directlyIf implementation is changed, client still uses list in same way as before
16 Java Class Library: The Interface List The standard package contains a list interface – called ListMethods provided
17 List Implementations That Use Arrays Chapter 5Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X
18 An Analogy Consider a classroom with 40 desks in fixed position Desks are wasted if less than 40 studentsNot enough desks if more than 40 studentsAn array is like the classroomEach desk an array location
19 Fig. 5-1 A classroom that contains desks in a fixed position. An AnalogyFig. 5-1 A classroom that contains desks in a fixed position.
20 An AnalogySuppose we have some students in classroom in order alphabeticallyWe add a new studentWe desire to maintain the alphabetic orderWe must shift some studentsWe remove a student in the middle of the sequenceAgain, we must shift some students
21 Adding a StudentFig. 5-2 Seating a new student between two existing students: at least one other student must move
22 The Java Implementation Private data fields for implementation of AListImplements interface ListInterface of Chapter 4View full specification source code
23 AList add() MethodsFirst add method adds a new item at the end of the listAssign new value at endIncrement length of listSecond add method adds item in mid-listRequires a utility method, makeRoom()This shifts elements ahead
24 Adding Items in Mid-list Fig. 5-3 Making room to insert Carla as third entry in an array.
25 Adding Items in Mid-list Fig An array of objects contains references to those objectsNote: figures in this text portray arrays as if they actually contained objects
26 The remove() Method View method remove() Must shift existing entries to avoid gap in the array – note method removeGap()Except when removing last entryMethod must also handle error situationsWhen position specified in the remove is invalidWhen remove() is called and the list is emptyInvalid call returns null value
27 Fig. 5-5 Removing Bob by shifting array entries. Removing a List EntryFig. 5-5 Removing Bob by shifting array entries.
28 Other Methods in AList Note other methods in the class Note implements java.io.SerializableTells compiler that instances of AList can be written to a file using object serialization
29 Expanding an Array An array has a fixed size When array becomes full If we need a larger list, we are in troubleWhen array becomes fullMove its contents to a larger array (dynamic expansion)Copy data from original to new locationManipulate names so new location keeps name of original array
30 Expanding an ArrayFig. 5-6 The dynamic expansion of an array copies the array's contents to a larger second array.
31 Expanding an ArrayFig (a) an array; (b) the same array with two references; (c) the two arrays, reference to original array now referencing a new, larger array
32 Expanding an ArrayCode to accomplish the expansion shown in Fig. 5-7, previous slide
33 A New Implementation of a List Change the isFull to always return falseWe will expand the array when it becomes fullWe keep this function so that the original interface does not changeThe add() methods will double the size of the array when it becomes fullNow declare a private method isArrayFullCalled by the add() methodsClick to view these methods
34 Java Class Library Has two classes that use dynamic array expansion ArrayListVectorBoth classesFound in java.utilImplement interface ListDefined in terms of a generic type
35 Using a Vector to Implement the ADT List Java's Vector class provides capabilities of an arrayAble to expand dynamicallyHides the details of the processVectorHas methods for manipulating entriesEnables implementing the ADT List
36 Using a VectorFig A client uses the methods given in ListInterface, but the implementation of the list uses Vector methods to perform its operations
37 Using a VectorView elements of the class definition VectorList <T>NoteConstructorsadd methodsreplaceremovegetEntry
38 Using a Vector The add() methods The remove() method The first uses the addElement method from the Vector classThe other uses the insertElementAt methodThe remove() methodUses the removeElementAt method
39 Pros and Cons of Array Use for the ADT List When using an array or vector …Retrieving an entry is fastAdding an entry at the end of the list is fastAdding or removing an entry that is between other entries requires shifting elements in the arrayIncreasing the size of the array or vector requires copying elements