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

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Chapter 7 – Arrays.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
© 2007 Lawrenceville Press Slide 1 Chapter 10 Arrays  Can store many of the same kind of data together  Allows a collection of related values to be stored.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
The Math Class Methods Utilizing the Important Math Operations of Java!
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Recitation 5 Enums and The Java Collections classes/interfaces 1.
ArrayLists (and the for-each loop) ArrayList example = new ArrayList (); example.add(4);
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
Grouping objects Introduction to collections 5.0.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
The ArrayList Data Structure Standard Arrays at High Speed!
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
Chapter 9 Introduction to Arrays Fundamentals of Java.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Chapter 7 – Arrays and Array Lists
Sixth Lecture ArrayList Abstract Class and Interface
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
COP 3503 FALL 2012 Shayan Javed Lecture 8
TCSS 143, Autumn 2004 Lecture Notes
Arrays versus ArrayList
Object Oriented Programming in java
slides created by Ethan Apter
ArrayLists 22-Feb-19.
Collections Framework
Review: libraries and packages
TCSS 143, Autumn 2004 Lecture Notes
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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