Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to.

Similar presentations


Presentation on theme: "Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to."— Presentation transcript:

1 Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to an ArrayList Object How to Access an Element Within an ArrayList How to Update an ArrayList Object Additional ArrayList Methods Printing or Concatenating an ArrayList Storing Primitives in an ArrayList ArrayList Example Using Anonymous Objects and a For-Each Loop ArrayList Objects Versus Standard Arrays 1

2 Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The LinkedList Class The List Interface Comparing Method Execution Times Queues, Stacks, and the ArrayDeque Class Overview of the Java Collections Framework Collections Example – Information Flow in a Network of Friends 2

3 The ArrayList Class The ArrayList class provides the basic functionality that comes with a standard array, plus it provides additional functionality. The basic functionality: An ArrayList stores an ordered collection of values and allows access to the values via an index. The added functionality: An ArrayList grows and shrinks dynamically by inserting and deleting elements at any specified location. 3

4 How to Create an ArrayList Object The ArrayList class is defined in the Java API's java.util package, so for files that use the ArrayList class, import it like this: import java.util.ArrayList; To initialize an ArrayList reference variable, in a declaration, use this syntax: ArrayList reference-variable = new ArrayList<>(); For example, here's how to initialize an ArrayList reference variable named students : ArrayList students = new ArrayList<>(); Use angled brackets to surround the type for the elements, and the type must be a class name (not a primitive). Use empty angled brackets (the diamond operator). 4

5 How to Create an ArrayList Object Let's compare the syntaxes for creating ArrayList objects, regular objects, and standard arrays. Here's the same ArrayList example as before: ArrayList students = new ArrayList<>(); Here's an object example: Mouse gus = new Mouse(); Here's a standard-array example: Student[] students = new Student[100]; 6

6 Adding Elements to an ArrayList Object To add an element to the end of an ArrayList object, use this syntax: ArrayList-reference-variable.add( item ); The item that's added must be the same type as the type specified in the ArrayList 's declaration. Write a code fragment that creates this ArrayList object: computerScientists 0"Ada Lovelace" 1"Grace Hopper" 2"Marissa Mayer" 7

7 Java API API stands for application programming interface. The Java API is the interface to the huge library of pre-built Java classes. As a programmer, you don't need to know the internals of those classes; you just need to know how to use them. Or said another way, you just need to know how to interface with them. To interface with them, you need to use their public methods. To use a method, you need to know what type of argument(s) to pass to it and what type of value it returns. A method's API shows the method's parameters and its return type. The standard way to show that information is to show the method's heading. For example, here's the API heading for the Math class's pow method: public static double pow(double num, double power) 8

8 How to Access an Element Within an ArrayList With standard arrays, you use square brackets to access and update an element. ArrayList objects don't use square brackets. Instead, they use a get method to access an element and a set method to update an element. Here's the API heading for the ArrayList 's get method: public E get(int index) Semantics: The index parameter specifies the position of the desired element within the ArrayList calling object. As with standard arrays, the first element is at position 0, the second element is at position 1, etc. If index refers to a nonexistent element, then a runtime error occurs. If index is valid, then get returns the element at the specified position. 9

9 How to Access an Element Within an ArrayList Note the E return type for the ArrayList 's get method: public E get(int index) The E stands for element. It represents the data type of the ArrayList 's elements. It's the same as the element-type specified in the ArrayList 's initialization: ArrayList reference-variable = new ArrayList<>(); 10

10 How to Update an ArrayList Object The set method allows you to assign a value to an existing ArrayList element. Here's its API heading: public E set(int index, E elem) Semantics: The index parameter specifies the position of the element you're interested in. If index refers to a nonexistent element, then a runtime error occurs. If index is valid, then set assigns the elem parameter to the specified element, overlaying whatever was there originally. E represents the data type of the ArrayList 's elements. 11

11 How to Update an ArrayList Object Draw a picture of the colors ArrayList after this code fragment executes: String mixedColor; ArrayList colors = new ArrayList<>(); colors.add("red"); colors.add("green"); colors.add("blue"); mixedColor = colors.get(0) + colors.get(1); colors.set(2, mixedColor); 12

12 Additional ArrayList Methods public void add(int index, E elem) Starting with the specified index position, shift the original elements to higher-indexed positions. Then insert the elem parameter at the specified index position. public void clear() Remove all elements from the list. public int indexOf(Object elem) Search for the first occurrence of the elem parameter within the list. If it's found, return its index position. If it's not found, return -1. public boolean isEmpty() Return true if the list contains no elements. public E remove(int index) Remove the element at the specified index position, shift all higher-indexed elements to lower-indexed positions, and return the removed element. public int size() Return the number of elements in the list. Object is a generic class that can be used as a class type for any object. 13

13 Example ArrayList Program import java.util.ArrayList; public class HungerGames { public static void main(String[] args) { int deceasedIndex; // index of deceased tribute String deceased; // name of deceased tribute ArrayList tributes = new ArrayList<>(); tributes.add("Cato"); tributes.add("Katniss"); tributes.add("Peeta"); tributes.add("Rue"); tributes.add(1, "Finnick"); deceasedIndex = (int) (Math.random() * tributes.size()); deceased = tributes.remove(deceasedIndex); System.out.println(deceased + " is no longer in the game."); System.out.println("Remaining: " + tributes); } // end main } // end HungerGames 15

14 Printing or Concatenating an ArrayList If you attempt to print or concatenate an ArrayList, the ArrayList returns a comma-separated list of ArrayList elements surrounded by square brackets, []. For example, in the HungerGames program, if Peeta is removed, the last line prints this: Remaining: [Cato, Finnick, Katniss, Rue] 16

15 Storing Primitives in an ArrayList As mentioned previously, ArrayList s store references. For example, in the HungerGames program, tribe is an ArrayList of strings, and strings are reference types. If you need to store primitives in an ArrayList, you can't do it directly, but you can do it if the primitives are wrapped in wrapper classes. Ever since Java 5.0, the "wrapping" process has been done behind the scenes. For ArrayList s, it's done automatically if a wrapper class is used in an ArrayList declaration. The StockAverage program on the next slide reads int stock values and stores them in an ArrayList. After all stock values are entered, the program calculates the average stock value. Why is an ArrayList appropriate for calculating a stock average? 17

16 Storing Primitives in an ArrayList import java.util.Scanner; import java.util.ArrayList; public class StockAverage { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); ArrayList stocks = new ArrayList<>(); double stock; // a stock value double stockSum = 0; // sum of stock values System.out.print("Enter a stock value (-1 to quit): "); stock = stdIn.nextDouble(); while (stock >= 0) { stocks.add(stock); System.out.print("Enter a stock value (-1 to quit): "); stock = stdIn.nextDouble(); } // end while Must be a wrapper class, not a primitive. Automatic boxing (“autoboxing”) takes place here. 18

17 Storing Primitives in an ArrayList for (int i=0; i<stocks.size(); i++) { stock = stocks.get(i); stockSum += stock; } if (stocks.size() != 0) { System.out.printf("\nAverage stock value = $%.2f\n", stockSum / stocks.size()); } } // end main } // end class StockAverage Where does automatic unboxing take place? 19

18 ArrayList Example Using Anonymous Objects and a For-Each Loop When storing objects in an ArrayList, it's common to create an object and add it to the ArrayList all in the same statement. For example, the upcoming BearStore program stores Bear objects in an ArrayList. In storing a Bear object, the program creates a Bear object and adds it to the bears ArrayList, all in the same statement: bears.add(new Bear("Acme", "brown teddy")); An anonymous object is an object that's instantiated, but it's not stored in a variable (and with no variable, there's no name for it; thus, we say it's "anonymous"). 20

19 ArrayList Example Using Anonymous Objects and a For-Each Loop import java.util.Scanner; import java.util.ArrayList; public class BearStore { ArrayList bears = new ArrayList<>(); //********************************************************** // Fill store with specified number of standard teddy bears. public void addStdBears(int num) { for (int i=0; i<num; i++) { bears.add(new Bear("Acme", "brown teddy")); } } // end addStdBears anonymous object 21

20 ArrayList Example Using Anonymous Objects and a For-Each Loop //********************************************************** // Fill store with specified number of customized bears. public void addUserSpecifiedBears(int num) { for (int i=0; i<num; i++) { bears.add(getUserSpecifiedBear()); } } // end addUserSpecifiedBears //********************************************************** // Prompt user for a customized bear name and return bear. private Bear getUserSpecifiedBear() { Scanner stdIn = new Scanner(System.in); String maker, type; System.out.print("Enter bear's maker: "); maker = stdIn.nextLine(); System.out.print("Enter bear's type: "); type = stdIn.nextLine(); return new Bear(maker, type); } // end getUserSpecifiedBear anonymous object 22

21 ArrayList Example Using Anonymous Objects and a For-Each Loop //********************************************************** // Print all the bears in the store. public void displayInventory() { for (Bear bear : bears) { bear.display(); } } // end displayInventory //********************************************************** public static void main(String[] args) { BearStore store = new BearStore(); store.addStdBears(3); store.addUserSpecifiedBears(2); store.displayInventory(); } // end main } // end BearStore class 23

22 ArrayList Example Using Anonymous Objects and a For-Each Loop public class Bear { private final String MAKER; // bear's manufacturer private final String TYPE; // type of bear //********************************************************** public Bear(String maker, String type) { MAKER = maker; TYPE = type; } public void display() { System.out.println(MAKER + " " + TYPE); } } // end Bear class 24

23 Anonymous Objects The bear store program contains several examples of using anonymous objects. In general, you'll see anonymous objects being used in two circumstances: Passing a newly created object into a method or constructor. For example: bears.add(new Bear("Acme", "brown teddy")); Returning a newly created object from a method. For example: return new Bear(maker, type); 25

24 For-Each Loop Note the for-each loop in the BearStore' s displayInventory method: public void displayInventory() { for (Bear bear : bears) { bear.display(); } } // end displayInventory For-each loop syntax for an ArrayList : for ( : ) Read this as "for each bear in bears, …" For each iteration through the loop, bear accesses the next element in the bears ArrayList. 26

25 For-Each Loop Note that using the for-each loop is an option, not a requirement. Here's an alternative displayInventory implementation that uses a standard for loop: public void displayInventory() { for (int i=0; i<bears.size(); i++) { bears.get(i).display(); } } // end displayInventory The for-each loop implementation is preferred because it is simpler. 27

26 ArrayList Objects Versus Standard Arrays Benefits of an ArrayList Over a Standard Array Benefits of a Standard Array Over an ArrayList 1. It's easy to increase the size of an ArrayList – just call add. 1. A standard array uses []'s to access array elements (which is easier than using get and set methods). 2. It's easy for a programmer to insert or remove an element to or from the interior of an ArrayList – just call add or remove and specify the element's index position. 2. A standard array is more efficient with storing primitive values. 28


Download ppt "Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to."

Similar presentations


Ads by Google