CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

Similar documents
Slides are adapted from the originals available at

Big O & ArrayList Fall 2018 Margaret Reid-Miller

Lesson 2.4 Arraylist

Intro to Computer Science II

Controls Structure for Repetition

ArrayLists. Chapter 12.1 in Savitch

Here is how we use an arraylist. To access the arraylist code we can import the class via:

Introduction to Computer Science I

Lesson 26: ArrayList (W08D1)

Lists using ArrayList

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

Arrays and ArrayLists. David Greenstein Monta Vista High School

CSE 143. Computer Programming II

PIC 20A Number, Autoboxing, and Unboxing

CS1083 Week 2: Arrays, ArrayList

CSE 1223: Introduction to Computer Programming in Java Chapter 6 Arrays

Dynamically sized arrays

CS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15)

Building Java Programs

Dynamic Arrays. Fundamentals of Computer Science

01. Which of the following statement describes dynamic resizing as is applies to the ArrayList class?

Java generics. h"p:// h"p://

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional)

Computational Expression

Lesson 43.. ArrayList

Using arrays to store data

Use of the ArrayList class

CS Programming I: ArrayList

Garbage Collection (1)

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

CSC 222: Object-Oriented Programming. Spring 2012

AP Programming - Chapter 13 Lecture page 1 of 17

STUDENT LESSON A15 ArrayList

CSE 143 Lecture 4. ArrayList. Reading: slides created by Marty Stepp

CSE 143 Lecture 4. Preconditions

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

1 Short Answer (10 Points Each)

CSSE 220 Day 8. Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop. Check out ArraysAndLists from SVN

Computer Science 210 Data Structures Siena College Fall 2018

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Dynamically sized arrays. Overview. The problem with arrays. Java library. The Java Library. Dynamically sized arrays. Normal Java arrays:

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

Java Coding 6. Collections

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Inf1-OP. Collections. Perdita Stevens, adapting earlier version by Ewan Klein. January 9, School of Informatics

The list abstract data type defined a number of operations that all list-like objects ought to implement:

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

Rigidity of arrays. Inf1-OP. ArrayList. ArrayList: Methods. Declaration. Collections

1.00/ Lecture 8. Arrays-1

AP Computer Science. ArrayLists

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Inf1-OP. Collections. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 6, School of Informatics

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Building Java Programs

REMINDER CS121/IS223. Agenda. A Recap on Arrays. Array of Cars for the Car Race? Arrays of Objects (i)

CS121/IS223. Collections Revisited. Dr Olly Gotel

Java generics. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

APCS Semester #1 Final Exam Practice Problems

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

CS 302: Introduction to Programming in Java. Lecture 12

Last Class. While loops Infinite loops Loop counters Iterations

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Working with arrays. ArrayLists. Abstraction. Arrays

CSSE 220. Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop. Check out ArraysListPractice from SVN

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

Object Oriented Programming. Java-Lecture 6 - Arrays

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Lecture 6: ArrayList Implementation

Java Collections Framework: Interfaces

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CSC 222: Object-Oriented Programming. Fall 2017

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12

Interfaces, collections and comparisons

Lesson 10: Quiz #1 and Getting User Input (W03D2)

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Building Java Programs

CSE 142 Su01 Final Exam Sample Solution page 1 of 7

CSE 1223: Exam II Autumn 2016

CS 211: Using ArrayList, Implementing Arraylist

Midterm Examination (MTA)

Array Based Lists. Collections

Example Program. public class ComputeArea {

CS 106A, Lecture 19 ArrayLists

COSC 123 Computer Creativity. Java Lists and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

4. Java language basics: Function. Minhaeng Lee

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Chapter 7 User-Defined Methods. Chapter Objectives

Methods. Every Java application must have a main method.

ECE 122. Engineering Problem Solving with Java

8/27/13. An intro to programming* *Java. Announcements. Professor Rodger. The Link. UTAs start TONIGHT!

Conditional Execution

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

Flow of Control: Loops. Chapter 4

CSE 8B Intro to CS: Java

Transcription:

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists 1

A programming problem Consider the following task: Double values representing grades are read until the user enters a negative number Then for all of the non-negative values entered, compute the following: The average, minimum and maximum grade The number of grades that are above average and below average The median grade 2

A programming problem If we knew how many grades there were going to be, we could use an array Recall what we know about arrays A sequence of variables of the same data type (e.g. int, double, String, boolean, etc.) Each variable in the array is called an element Array elements are accessed through their index 0 9 3

A programming problem But we don t know how many grades there will be We just want to keep reading until we find a negative score An array requires us to know before we start using it how big it will be We need to declare it with a specific size double[] grades = new double[30]; What we would like to have is an array that can change size as we use it 4

A programming problem In Java, we can use an ArrayList Just like an array, except it can change size when we need it to Also known as a dynamic array No need to pre-determine the number of elements up front, just add to the array as we need it 0 5

A programming problem In Java, we can use an ArrayList Just like an array, except it can change size when we need it to Also known as a dynamic array No need to pre-determine the number of elements up front, just add to the array as we need it 0 1 6

A programming problem In Java, we can use an ArrayList Just like an array, except it can change size when we need it to Also known as a dynamic array No need to pre-determine the number of elements up front, just add to the array as we need it 0 2 7

ArrayLists So what does this have to do with ArrayLists? ArrayList is a Java class Part of the Java Standard Library It implements a dynamic array To use an ArrayList we need to know how to use it: How do we declare it? How can we put things into an ArrayList? How can we read things from an ArrayList? 8

ArrayLists A programming problem Let s consider another programming problem We want code that reads in text one line at a time until the user enters the word stop Then the code should repeat back all of the lines in reverse order We do not know how many lines of text there will be before we start We can solve this with an ArrayList 9

ArrayList A programming Problem import java.util.arraylist; public static void main(string [] args) { ArrayList<String> stringlist = new ArrayList<String>(); Scanner keyboard = new Scanner(System.in); String input = ; while (!input.equals( stop )) { input = keyboard.nextline(); stringlist.add(input); int i = stringlist.size()-1; while (i>0) { System.out.println(stringList.get(i)); i = i - 1; 10

ArrayList A programming Problem import java.util.arraylist; public static void main(string [] args) { ArrayList<String> stringlist = new ArrayList<String>(); Scanner keyboard = new Scanner(System.in); String input = ; while (!input.equals( stop )) { input = keyboard.nextline(); stringlist.add(input); int i = stringlist.size()-1; while (i>0) { System.out.println(stringList.get(i)); i = i - 1; import? 11

ArrayList - import To use an ArrayList we first need to import it ArrayList is a class that is part of the Java standard library Just like Scanner We need to tell our program that we re going to use it 12

ArrayList A programming Problem import java.util.arraylist; public static void main(string [] args) { ArrayList<String> stringlist = new ArrayList<String>(); Scanner keyboard = new Scanner(System.in); String input = ; while (!input.equals( stop )) { input = keyboard.nextline(); stringlist.add(input); <String>? int i = stringlist.size()-1; while (i>0) { System.out.println(stringList.get(i)); i = i - 1; 13

ArrayList - Declaration What about this <String>? This syntax indicates that the class you are using is a generic class ArrayList<E> - <E> is the placeholder for the class Can be used with any class Cannot be used with primitive types (int, boolean, char) We ll see what to do with these in a moment You can think of it as replacing the array type declaration: String[] stringarr = new String[10]; ArrayList<String> stringl = new ArrayList<String>(); 14

ArrayList Some Sample code import java.util.arraylist; public static void main(string [] args) { ArrayList<String> stringlist = new ArrayList<String>(); Scanner keyboard = new Scanner(System.in); String input = ; while (!input.equals( stop )) { input = keyboard.nextline(); stringlist.add(input); add()? int i = stringlist.size()-1; while (i>0) { System.out.println(stringList.get(i)); i = i - 1; 15

ArrayList - Methods add is the main method used to add elements to an ArrayList: boolean add(e obj) Adds an element to the end of the ArrayList E is whatever type we declared with the ArrayList Returns true if it is able to add it, false if not No real equivalent in arrays, since arrays aren t dynamic 16

ArrayList A programming Problem import java.util.arraylist; public static void main(string [] args) { ArrayList<String> stringlist = new ArrayList<String>(); Scanner keyboard = new Scanner(System.in); String input = ; while (!input.equals( stop )) { input = keyboard.nextline(); stringlist.add(input); int i = stringlist.size()-1; while (i>0) { System.out.println(stringList.get(i)); i = i - 1; get()? 17

ArrayList - Methods get is the method used to access elements : E get(int index) Access an element at position index in the ArrayList Returns the element at the given index E is the type you used when you declared the ArrayList Equivalent to accessing an array via a subscript: System.out.println(stringArr[index]); System.out.println(stringL.get(index)); Be carefu! Just like arrays your code 18

ArrayList A programming Problem import java.util.arraylist; public static void main(string [] args) { ArrayList<String> stringlist = new ArrayList<String>(); Scanner keyboard = new Scanner(System.in); String input = ; while (!input.equals( stop )) { input = keyboard.nextline(); stringlist.add(input); int i = stringlist.size()-1; while (i>0) { System.out.println(stringList.get(i)); i = i - 1; size()? 19

ArrayList - Methods We also need to have a way to check how long our ArrayList is: int size() Returns back the count of elements in the ArrayList Equivalent to using the array length attribute: int c = stringarr.length; int c = stringl.size(); 20

ArrayList - Methods Since ArrayLists are dynamic, there s a second method for adding elements: void add(int index, E obj) Adds an element at position index Moves everything currently in the ArrayList from index on to the right one position to insert the new element into place E is the type used when you declared the ArrayList No real equivalent in arrays, since arrays aren t dynamic 21

ArrayList - Methods We also want some way of changing elements at a position: E set(int index, E obj) Changes the element at position index to the new value obj E is the type used when you declared the ArrayList Returns back what was previously stored at that index Equivalent to using the array subscript: stringarr[index] = obj; stringl.set(index,obj); 22

ArrayList - Methods Because ArrayLists are dynamic, we can delete elements from them: E remove(int index) Removes the element at index from the list Everything to the right of index is shifted one position left to fill the gap Returns back what we ve removed No real equivalent in arrays because arrays are not dynamic 23

Your Turn - ArrayLists Write a segment of code that takes an ArrayList of Strings named list and determines: The length of the longest String in the list The length of the shortest String in the list The average length of Strings in the list Compute the average as a double value You can assume that the ArrayList has already been declared and is named list 24

Your Turn - ArrayLists 25

Your Turn ArrayLists (for loop) 26

Your Turn Again - ArrayLists Write a segment of code that takes an ArrayList of Strings named list and removes any Strings that are longer than 5 characters 27

Your Turn Again - ArrayLists int i=0; while (i<list.size()) { String current = list.get(i); if (current.length()>5) { list.remove(i); i = i + 1; 28

Your Turn Again - ArrayLists int i=0; while (i<list.size()) { String current = list.get(i); if (current.length()>5) { list.remove(i); i = i + 1; Wait does this work? 29

Your Turn Again - ArrayLists int i=0; while (i<list.size()) { String current = list.get(i); if (current.length()>5) { list.remove(i); i = i + 1; Wait does this work? Why won t this work? 30

Removing elements from a list We need to be careful removing elements from an ArrayList Remember when we remove elements, the entire ArrayList shifts into the position of the removed element: remove(6); 0 1 2 3 4 5 6 7 8 9 0 6 9 31

Removing elements from a list We need to be careful removing elements from an ArrayList Remember when we remove elements, the entire ArrayList shifts into the position of the removed element: remove(6); 0 1 2 3 4 5 7 8 9 0 6 9 32

Removing elements from a list We need to be careful removing elements from an ArrayList Remember when we remove elements, the entire ArrayList shifts into the position of the removed element: remove(6); 0 1 2 3 4 5 7 8 9 0 6 8 33

Removing elements from a list We need to be careful removing elements from an ArrayList remove(6); The item at position 6 is removed. Now the item that was at position 7 is at position 6 We will end up skipping this element in our loop 0 1 2 3 4 5 7 8 9 0 6 8 34

Your Turn Again - ArrayLists Fix this segment of code so that it doesn t skip any values int i=0; while (i<list.size()) { String current = list.get(i); if (current.length()>5) { list.remove(i); i = i + 1; 35

A programming problem - revisited Let s reconsider the problem from the start of these slides: Double values representing grades are read until the user enters a negative number Then for all of the non-negative values entered, compute the following: The average, minimum and maximum grade The number of grades that are above average and below average The median grade For this we need an ArrayList of primitive types 36

ArrayList Example import java.util.arraylist; public static void main(string [] args) { ArrayList<Double> gradelist = new ArrayList<Double>(); Scanner keyboard = new Scanner(System.in); double input = Double.parseDouble(keyboard.nextLine()); while (input>=0.0) { gradelist.add(input); input = Double.parseDouble(keyboard.nextLine()); int i = 0; int total = 0; while (i<gradelist.size()) { total = total + gradelist.get(i)); i = i + 1; double average = total/i; 37

ArrayList Example import java.util.arraylist; public static void main(string [] args) { ArrayList<Double> gradelist = new ArrayList<Double>(); Scanner keyboard = new Scanner(System.in); double input = Double.parseDouble(keyboard.nextLine()); while (input>=0.0) { gradelist.add(input); input = Double.parseDouble(keyboard.nextLine()); int i = 0; int total = 0; while (i<gradelist.size()) { total = total + gradelist.get(i)); i = i + 1; double average = total/i; <Double>? 38

Collections - ArrayList ArrayLists are used to hold objects We cannot use them to hold primitive types ArrayList<double> gradelist = new ArrayList<double>(); 39

Collections - ArrayList ArrayLists are used to hold objects We cannot use them to hold primitive types ArrayList<double> gradelist = new ArrayList<double>(); However, each primitive type has a wrapper class that we can use int class Integer char class Character double class Double 40

Digression Wrapper classes Used to transform a primitive type into a class Useful for generic classes (like collections) that require a class and can t use a primitive 41

Digression Wrapper Classes Taking a primitive data element and wrapping it up in a wrapper class is known as boxing Double mydouble = new Double(6.0); Taking the primitive out of the wrapper is known as unboxing double myprimitive = mydouble.doublevalue(); Java will (usually) automatically do the right thing on its own (autoboxing) Double mydouble = 6.0; double myprimitive = mydouble; double sum = mydouble + 3.0; 42

ArrayLists ArrayLists are used to hold objects We cannot use them to hold primitive types ArrayList<int> intlist = new ArrayList<int>(); 43

Collections - ArrayList ArrayLists are used to hold objects We cannot use them to hold primitive types ArrayList<double> gradelist = new ArrayList<double>(); Instead we use the wrapper object: ArrayList<Double> gradelist = new ArrayList<Double>(); 44

ArrayLists If we need an ArrayList of primitives, we use the corresponding wrapper class instead But we can use autoboxing to make our life easier adding and examining elements public static void main(string [] args) { ArrayList<Double> gradelist = new ArrayList<Double>(); intlist.add(12.0); double firstscore = gradelist.get(0); 45

Your Turn - ArrayLists Write a piece of code that: Declares a new ArrayList of integers named nums Puts the even numbers from 2 through 20 into this list 46

Your Turn - ArrayLists Write a piece of code that: Uses an ArrayList of Integers named list1 to build a new ArrayList of Integers named list2 The elements of list2 should be in reverse order from the elements that are in list1 47

ArrayLists and Methods Like arrays, ArrayLists can be passed as parameters to methods and can be returned by methods (functions) e.g. private static void printlist(arraylist<double> al) private static ArrayList<Integer> copylist(arraylist<integer> al) private static int indexofmin(arraylist<integer> al) private static void sort(arraylist<character> al) 48

ArrayList Example On the following slide is some code that uses an array Rewrite this code so that it uses an ArrayList instead 49

ArrayList Example public class ArrayExample { public static int countoccurrences(char [] array, char ch) { int chcount=0; for (int loopcount=0; loopcount<array.length; loopcount++) { if( array[loopcount] == ch ) { chcount=chcount+1; return chcount; public static void main(string [] args) { char [] mychars = new char[4]; mychars[0]= c ; mychars[1]= b ; mychars[2]= b ; mychars[3]= a ; char mych = b ; int count = countoccurrences(mychars,mych); System.out.println( The number of occurrences is: +count); 50

ArrayList Example One solution 51