Imagine that you have a part-time job at the local movie rental store. Realizing that you know a good deal about computers, the store owner asks you to wnte an interactive program that will maintain the store's inventory of DVDs that are for sale. The inventory consists of a list of movie titles and the following information associated with each title: 5.4 Application: Maintaining an Inventory Have value: number of DVDs currently in stock. . Want value: number of DVDs that should be in stock. (When the havc value is less than the want value, more DVDs are ordered.) Wait list: list of names of people waiting for the title if it is so Because the owner plans to turn off he power to the computer wherhercice. is closed, your inventory program will not be running at all times. inates and the program must save the inventory in a file before execution term later restore the inventory when it is run again. terminates and Program input and output are as follows: Input - A file that contains a previously saved inventory A file that contains information on an incoming ship command D.) Single-letter commands-with arguments where about or modify the inventory and that the user will enter coming shipment of DVDs. necessary-that in Realize, however, that you cannot complete one stage in to the others Also realize that at many steps in the devele you must make choices. Although the following discus impression that the choices are clear cut, this is not always t both the trade ofs between choices and the false starts (wre ered) are often numerous 286 Chapter 5 Linked Lists steps in the development of a tollowing discussion may give th tarts (wrong choices conid the case. In narily ivolves data management and requires This problem primarily involves program commands. These commands suggest the following opcratioms Opserations on theLst the iventory in alphabetical order by title (L.command) comman Replace the inventory item associated with a title (M, D, R, and S Insert new inventory items (A and D commands) Recall that each title might have an associated wait list of people who a waiting for that title. You must be able to .Add new people to the end of the wait list when they want a DVID that inventory Find the inventory item associated with a title (I, M, D, O, and S sold out (S command ). - Delete people from the beginning of the wait list when new DVD, a delivered (D command) . Display the names on a wait list for a particular title (I and L commands In addition, you must be able to a Save the current inventory and associated wait lists when program cat tion terminates (Qcommand). . Restore the current inventory and associated wait lists when program cution begins again You coald think of these operations as part of an ADT in next step shoald be to specify cach of the operations fully. Since t about linked lists and implementation issues, the completion of Tur tions will be left as an exercise. We will turn our attention to a dae that could implement the inventory. Each data item in the ADT inventory represents a movie and conta the number of DVDs in stock (a have value), the number desir de and a wait list. How will you represent the wait list? First, you to keep telephone number of the person. This class might be structu publie class Customer formation you want to store in the wait list. For example, y custoner containing data fields for the first and last the full name and phone number of each person ndre A customer private String lastiame: and last names along wait list Application Maintaining an Inventory 287 private String firstName private String phone c customer (String first, String last, String phone) 1 to be implemented omer( ) end constructor public String tostring) // to be implemented I end tostring ) I end class Customer This definition contains the minimum number of methods required to use instances of the customer class in our inventory problem. You may also decide that you want to keep additional information about a person, such as their address. The tostring method is provided for printing purposes Now that you have decided what information to keep in the wait list, how will you implement the wait list itself in the ADT inventory? Could you use any of the implementations of the ADT list we developed previously? To make this decision, you must review the requirements of the wait list as stated in the inventory problem and then see if the ADT list will be able to meet these requirements. The inventory problem requires you to be able to add to the end of the wait list and delete from the beginning of the wait ist. Clearly, removing an item from the beginning of the list is easy: You can simply use the ADT list operation remove with an index value of 1 dding an item to the end of the list is also fairly easy. You know the size of e list from the ADT list operation size), and you could use the ADT list treration add with an index valuc of sizec) the wait list ist the I to place an item at the end of One of the requirements of the inventory problem is that the L command The ADT list is not ADT list in a way that will support this requirement? Not casily, since the data that must be in DT l inventory in alphabetical order by movie title. Will you be able to use the best choice for alphabetical order list is based on index position, not on a sorted order. A better choice is )1 sorted list. Not only does it maintain the data in a sorted order for it also provides an operation locateIndex(item) that can be used to the AD)T sprted list operation earch for an item in the sorted list implementation or a reference-based implementation? If you use arn contain the items, you can use a binary search. Inserting and deleting requires you to shift array elements. Using a linked list for the ics these data shifts but makes a binary search impractical. (How do loca the middle item in a linked list?) Weighing these trade -ofs, baed eAT sorted list is not yet implemented, should you use an array- based array to tems, however you nked list to implement the ADT sorted list 288 Chapter 5 Linked Lists ze, we have made the following choices: . The inventory is a sorted list of data items (the ADT sorted list int as a linked ist of data items), sorted by the title that each ee . Each inventory item contains a title, a have value, a want valye A sorted list represents the represe of customers (the wait list) Figure 5.30 and the following Java statements summarize these choices. lang.Comparable ( public class Stockitem implements java.lang.c private String title; private int have, want; private ListReferenceBased waitingtist // various constructors for StockItem Inventory ist node waitingList node ite titie have want vaitingtist Person Stoekiten iten Inventory list ntory list node,(b) wait ist node: (c) orthogonal structure for the invento e for the inventory 290 Chapter 5 Linked Lists System.out.printin(e) ) end catch toring the inventory is also straightforward ListReferenceBased restoredInventory try f Objectinputstream oisnew object InputStream(fis) object o - ois.readobject) restoredInventory (istReferencedBased) o System.out.println(restoredInventory); FileInputstream fis new FileInputstream("inventory,dat" ) / end try catch (Exception e) System.out.println(e)i ) I end cateh Th oltion s ei i an ecise 5.5 The Java Collections Framework Many modern programming languages, such as Java, provide classes that imple ment many of the more commonly used ADTs. In Java, many of these dlaso are detined in the Java Collections Framework or JCE. The JCF contains The Java Collec- tions Framework number of classes and interfaces that can be applied to nearly any type of dan (JCF) provides Many of the ADTs that are presented in this text have a corresponding classes for common class or interface in the JCF. For example, a List interface is defined in t ADTs JCF that is similar to the Listinterface specification presented earlicr in th ths chapter. You may be wondering why we spend so much time developing in this text if they are already provided in the JCF. There are many reasons ADT doing so; here are just a few: . Developing simple ADT's provides a foundation for learning o . You may find yourself working in a language that does not pro other ADT predefined ADTs. You need to have the ability to develop ADIS own, and hence understand the proces ADTs on nguage you are using are not sufficient. tramework is a unified architecture for represeco If the ADTs defined by the la may need to develop your own or e nhance existing ones. A collections frame- work includes collections. It includes interfaces, or implementations, or concrete implementations of co nterfaces Lons W algorithus, or methods that imple s, or methods that perform useful computations, andarching, on objects that implement collection interfaces. llection interfaies a algortens worplhie because the same method can be used on many tations of the appeopriate collections interface algorithms ne y different i The Java Collections Framework 291 the contents of a bricf overview of generics and iterators CF also contains iterators. Iterators provide a way to cycle through collection. Before we can discuss the JCF further, we will give Generics elies heavily on Java generics. Generics allow you to develkop classes Generic clases terfaces and defer certain data type information until you are actually allow data-type gady to use the dlass or interface. For example, our list interface was devel information to be t items by using the object class. ics, this data type is left as a data-type parameter in the definition of With gener the class or interface lowed by
private E theData; private int n; public Kyclass) 1 // end constructor public Myclass (E initData, int num) nnum theData-initData; 17 end constructor Public void setData(E newData) f ) II end setData public E getData) theData newData; return theData: I end get Data public int gethum) return n 1 end get.Num 1 11 end Myclass nd ta type tyou (the client) declare instances of the class, you specify the actual Ope, onl that the parameter represents. This data type cannot be a primitive Ony object types 9 describes in more detail how to create your own generics nd nd type parameters generic class could begin as ypes are allowed. For example, a simple program that uses are allowed for data 292 Chapter 5 Linked Lists Myclasasstring' a new yClassestring; Double d new Double(6.4) statie publie void main(stringt I arga) 51); new MyClass (d, ble> b= MyClass boolean hasNext) // Returns true if the iteration has more elements. next ( ); // Returns the next element in the iteration. void remove() throws UnsupportedoperationException. II elenent returned by the iterator (optional II operation). end Iterator Removes from the underlying collection the last IllegalStateException The method next is retu n an iterator is initially created, it is positioned so that the first used to return the next element in the on the iterator object will retur method hastlext can be used to determine if another e the initial element in the col the collection UnsupportedoperationException. The expectation is that class that implements the interface llo Notice that one of the operations, remove, can hrow Unsupported itera- tor methods will throw an exceptiorn notincall to pext ment is available on tion will simply throw this exception if the operation is o the exceptio the remove opcr not available in The Java Collections Framework 293 are an integral part of all of the classes and interfaces used esenting collections in the JCE. Note that just as you can use inherit- e new classes, you can use inheritance to derive new interfaces, subinterfaces. The basis for the ADT collections in the JCF is ace java.util.Iterable, with the subinterface java.uti.1 classes ance to derive ofen the interface collection lic interface IterableE Iterator iterator rns an iterator over the elements in this collection ) I/ end Iterable pablic interface collection / only a portion of the collection interface is shown here. /I See the J2SE documentation for a conplete listing of // nethods boolean add (E o) /I Ensures that this collection contains the specified // element (optional operation) boolean remove (Object o) / Removes a single instance of the specified element from // this collection, if it is present (optional operation). void clear) Removes all of the elements from this collection / (optional operation). boolean contains(object o) Returns true if this collection contains the specified // elenent // boolean equals(Object o) // Conpares the specitied object with this collection for I equality s true if this collection contains no clements. int sizet)i ns the number of elements in this collection. Object toArray) an array containing all of the elements in this I collection. end Collection a method to return an 294 Chapter 5 Linked Lists Thus, every ADT collection in the JCF will tor object for the underlying collection. The following exam iterator can he used with the ICF list class Linkediist: hos import java . ut1.Linkedlist; import java.util.Iteratori public elass TestLinkedList statie publie void main(Stringt1 args) tinkedList myList - new LinkedList extends Iterator iterator() // Returns an iterator over the elementa in this proper sequence ListiteratorcE listiterator) / Returns a list iterator of the elements 11 proper sequence) n this listin in this list The Java Collections Framework 297 ator listrterator(int index) ListIterato / proper // this list. a list iterator of the elementa in this list (in r sequence), starting at the specified position in s remove( int index) //Removes the element at the specified position in this list I (optional operation). boolean remove(Object o): Renoves the first occurrence in this liat of the specified 1 element (optional operation) s set (int index, E element); places the elenent at the specified position in this // list with the specified element (optional operation). int size / Returns the number of elements in this liat. ListcE> subList (int fromIndex, int toindex): // Returns a view of the portion of this liat between the / specified fromIndex, inclusive, and tolndex. // exclusive objectl toArray) // Returns an array containing all of the elements in this // list in proper sequence. end List The JCF provides numerous classes that implement the List interface, g inkedList, ArrayList, and vector. Here is an example of how the JCF class Arraytist is used to maintain a grocery list: aport java.util.ArrayList: laport java.util.Iteratori public class GroceryList i static Public void main(stringt args) f lteratort groceryList a Iterator iter new ArrayList0; grocerytist.add( "apples") groceryList.add( bread") groceryList.add( juice") 298 Chapter 5 Linked Lists groceryl.ist.addi "carrots") groceryl.ist.add ice crean") System.out.println "Mumber of items on my grocery + groceryList.size)) System.out-printin("Items are: iter-groceryList.listlterator(); while ( iter . hasNext()) string nextitem iter.next(O systen.out.printintgroceryList.indexof (nextre + nextItem): / end while // end main I end GroceryList The output of this program is Number ot items on my grocery list: 5 Items are 0) apples 1) bread 2) juice 3) carrots 4) ice erean Clearly it is more efficient to use a counter to number the items than to us the method indexof, it was done for illustrative purposes. Summary 1. You can use reference variables to implement the data structure known list by using a class definition such as the following: package Lists class sode private E theData; private int n; public Kyclass) 1 // end constructor public Myclass (E initData, int num) nnum theData-initData; 17 end constructor Public void setData(E newData) f ) II end setData public E getData) theData newData; return theData: I end get Data public int gethum) return n 1 end get.Num 1 11 end Myclass nd ta type tyou (the client) declare instances of the class, you specify the actual Ope, onl that the parameter represents. This data type cannot be a primitive Ony object types 9 describes in more detail how to create your own generics nd nd type parameters generic class could begin as ypes are allowed. For example, a simple program that uses are allowed for data 292 Chapter 5 Linked Lists Myclasasstring' a new yClassestring; Double d new Double(6.4) statie publie void main(stringt I arga) 51); new MyClass (d, ble> b= MyClass boolean hasNext) // Returns true if the iteration has more elements. next ( ); // Returns the next element in the iteration. void remove() throws UnsupportedoperationException. II elenent returned by the iterator (optional II operation). end Iterator Removes from the underlying collection the last IllegalStateException The method next is retu n an iterator is initially created, it is positioned so that the first used to return the next element in the on the iterator object will retur method hastlext can be used to determine if another e the initial element in the col the collection UnsupportedoperationException. The expectation is that class that implements the interface llo Notice that one of the operations, remove, can hrow Unsupported itera- tor methods will throw an exceptiorn notincall to pext ment is available on tion will simply throw this exception if the operation is o the exceptio the remove opcr not available in The Java Collections Framework 293 are an integral part of all of the classes and interfaces used esenting collections in the JCE. Note that just as you can use inherit- e new classes, you can use inheritance to derive new interfaces, subinterfaces. The basis for the ADT collections in the JCF is ace java.util.Iterable, with the subinterface java.uti.1 classes ance to derive ofen the interface collection lic interface IterableE Iterator iterator rns an iterator over the elements in this collection ) I/ end Iterable pablic interface collection / only a portion of the collection interface is shown here. /I See the J2SE documentation for a conplete listing of // nethods boolean add (E o) /I Ensures that this collection contains the specified // element (optional operation) boolean remove (Object o) / Removes a single instance of the specified element from // this collection, if it is present (optional operation). void clear) Removes all of the elements from this collection / (optional operation). boolean contains(object o) Returns true if this collection contains the specified // elenent // boolean equals(Object o) // Conpares the specitied object with this collection for I equality s true if this collection contains no clements. int sizet)i ns the number of elements in this collection. Object toArray) an array containing all of the elements in this I collection. end Collection a method to return an 294 Chapter 5 Linked Lists Thus, every ADT collection in the JCF will tor object for the underlying collection. The following exam iterator can he used with the ICF list class Linkediist: hos import java . ut1.Linkedlist; import java.util.Iteratori public elass TestLinkedList statie publie void main(Stringt1 args) tinkedList myList - new LinkedList extends Iterator iterator() // Returns an iterator over the elementa in this proper sequence ListiteratorcE listiterator) / Returns a list iterator of the elements 11 proper sequence) n this listin in this list The Java Collections Framework 297 ator listrterator(int index) ListIterato / proper // this list. a list iterator of the elementa in this list (in r sequence), starting at the specified position in s remove( int index) //Removes the element at the specified position in this list I (optional operation). boolean remove(Object o): Renoves the first occurrence in this liat of the specified 1 element (optional operation) s set (int index, E element); places the elenent at the specified position in this // list with the specified element (optional operation). int size / Returns the number of elements in this liat. ListcE> subList (int fromIndex, int toindex): // Returns a view of the portion of this liat between the / specified fromIndex, inclusive, and tolndex. // exclusive objectl toArray) // Returns an array containing all of the elements in this // list in proper sequence. end List The JCF provides numerous classes that implement the List interface, g inkedList, ArrayList, and vector. Here is an example of how the JCF class Arraytist is used to maintain a grocery list: aport java.util.ArrayList: laport java.util.Iteratori public class GroceryList i static Public void main(stringt args) f lteratort groceryList a Iterator iter new ArrayList0; grocerytist.add( "apples") groceryList.add( bread") groceryList.add( juice") 298 Chapter 5 Linked Lists groceryl.ist.addi "carrots") groceryl.ist.add ice crean") System.out.println "Mumber of items on my grocery + groceryList.size)) System.out-printin("Items are: iter-groceryList.listlterator(); while ( iter . hasNext()) string nextitem iter.next(O systen.out.printintgroceryList.indexof (nextre + nextItem): / end while // end main I end GroceryList The output of this program is Number ot items on my grocery list: 5 Items are 0) apples 1) bread 2) juice 3) carrots 4) ice erean Clearly it is more efficient to use a counter to number the items than to us the method indexof, it was done for illustrative purposes. Summary 1. You can use reference variables to implement the data structure known list by using a class definition such as the following: package Lists class sode