import java.util.*; // CSE 143, Summer 2016 // // A mysterious program used to play with reference semantics. // I encourage you to change things around and see what you get! public class ReferenceMystery { public static void main(String[] args) { // new = creating new list! ArrayList groceries = new ArrayList(); groceries.add("cookies"); groceries.add("milk"); groceries.add("pizza"); groceries.add("ice cream"); groceries.add("tomato"); System.out.println("food: " + groceries); System.out.println(); // creating a REFERENCE to the same list, groceries // We now have two variables, groceries and sameGroceries, // that reference the same ArrayList. List sameGroceries = groceries; sameGroceries = groceries; checkGroceries(sameGroceries); System.out.println("food: " + groceries); // Here are more cases we talked about in class. // This uses an ArrayList constructor to copy "groceries". // They no longer reference the same list. Any changes made // to otherGroceries will not be reflected in groceries. List otherGroceries = new ArrayList(groceries); // In another attempt to copy the list, we tried this. This however // does something really never desired: we create a new list, // and immediately lose it by changing the REFERENCE of yetMoreGroceries. // In the end, yetMoreGroceries just references groceries, and // we've lost forever the reference to the new Arraylist we // created. List yetMoreGroceries = new ArrayList(); yetMoreGroceries = groceries; } // Checks all groceries to make sure you're not eating too // much junk food! // pre : groceries != null // post: removes junk food that isn't good for you public static void checkGroceries(List groceries) { for (int i = 0; i < groceries.size(); i++) { if (groceries.get(i).equals("cookies")) { // you can't have cookies groceries.remove(i); } } // You can have Joe Joe's. They're just as good. groceries.add("Joe Joe's"); } }