Lab 23
Background
Arrays in Java are efficient but inconvenient: once created, their size cannot be changed. Sometimes you don't know in advance how many elements you'll need, and it's wasteful to allocate large amounts of unused memory. Fortunately the Java library provides an extensive Collections Framework for storing not only arrays of objects, but many other types of data structures. ArrayList is a generic collection of objects: the declaration determines the type of object it will store:
ArrayList<String> list; list = new ArrayList<String>();
The ArrayList class provides many methods for adding, getting, setting elements. For example:
String[] array; | ArrayList<String> list; | ||
---|---|---|---|
array.length | The capacity of the array. | list.size() | The number of elements stored in the ArrayList. |
String val = array[0]; | String val = list.get(0); | ||
array[0] = "HI"; | list.set(0, "HI"); | ||
Not possible to resize an array. | list.add("Bob"); | Adds a new element at the end of the list. (This changes the size.) | |
Not possible to resize an array. | list.remove(4); | Removes the element at index 4. (all elements after 4 shift left.) |
As with arrays, you can use an extended for loop to iterate the elements:
for (String text : list) { System.out.println(text); }
Instructions
The goal of this lab is to implement a Document class that represents a plain text file as an ArrayList of String objects. Each entry in the ArrayListcorresponds to a single line of text.The following files are provided:
-
Document.java - UNFINISHED
-
DocumentTestDriver.java - This is a simple driver class. Take a minute to look over this code to get a better idea of the expected behavior.
-
Editor.java - This is an editor application that provides a command-line interface to the Document class.
Download the files above and complete Document.java so that all methods conform to the Javadoc comments. Test your completed file by running the two provided applications. The file output.txt contains the correct output for DocumentTestDriver.java.
Submit your completed version of Document.java through Web-CAT. If you have trouble with your submission, you may find it helpful to look at the JUnit submission tests: DocumentTest.java.
Acknowledgement
This lab is based on materials developed by Nathan Sprague.