Objective: Use the ArrayList class
Run the following example in BlueJ, make sure you understand how it works!
import java.util.*; /** * Use ArrayList class to Implement GroceryList */ public class GroceryList { private ArrayList< String > groceries; public GroceryList() { groceries = new ArrayList(); } /** * <<< size >>> returns the number of elements in the list */ public int numberOfItems() { return groceries.size(); } /** * <<< add >>> add an item to the end of the list and always returns true */ public boolean addItem(String item) { return groceries.add(item); } /** * <<< add >>> inserts an item to the list at position specified */ public void addItem(int index, String item) { groceries.add(index, item); } /** * <<< get >>> returns the element at the specified index */ public String getItem(int index) { return groceries.get(index); } /** * <<< set >>> replaces item at index with specified element * returns replaced element */ public String setItem(int index, String item) { return groceries.set(index,item); } /** * remove item at specified index */ public String removeItem(int index) { return groceries.remove(index); } /** * returns list of items */ public String toString() { String s = ""; for (int i = 0; i < groceries.size(); i++) { s += groceries.get(i) + " "; } if (groceries.size() == 0) { s = "<<< no groceries on the list >>>"; } return s; } }
public class ListTester { public static void main(String[] args) { //Create a new grocery list GroceryList myList = new GroceryList(); //Print out the list System.out.println("Grocery list: " + myList); //Add some items myList.addItem("eggs"); myList.addItem("bacon"); myList.addItem("coffee"); //Print out the list System.out.println("Grocery list: " + myList); //Print number of items in list System.out.println("Number of items: " + myList.numberOfItems()); //Add some items at various positions myList.addItem(1,"pickles"); myList.addItem(2,"chips"); //Print out the list System.out.println("Grocery list: " + myList); // get item at position 3 System.out.println(myList.getItem(3)); // replace item at position 3 System.out.println(myList.setItem(3,"meat")); //Print out the list System.out.println("Grocery list: " + myList); // remove item 0 System.out.println(myList.removeItem(0)); //Print out the list System.out.println("Grocery list: " + myList); } }