ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12

Similar documents
Working with arrays. ArrayLists. Abstraction. Arrays

Computational Expression

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Introduction to Computer Science I

Array Based Lists. Collections

Computer Science 210 Data Structures Siena College Fall 2018

CS 302: Introduction to Programming in Java. Lecture 12

CITS1001 week 4 Grouping objects

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

ArrayLists. Chapter 12.1 in Savitch

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

CS 211: Using ArrayList, Implementing Arraylist

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

CS Programming I: ArrayList

Slides are adapted from the originals available at

Using arrays to store data

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

Collections, Maps and Generics

Building Java Programs

Algorithms. Produced by. Eamonn de Leastar

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

AP Computer Science. ArrayLists

Lesson 26: ArrayList (W08D1)

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

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

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

Objects and State. COMP1400 Week 9. Wednesday, 19 September 12

Lecture Multidimensional Arrays and the ArrayList Class. Dr. Martin O Connor CA166

CS 200 Objects and ArrayList Jim Williams, PhD

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

Intro to Computer Science II

Unit5: Packages and abstraction. Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15

CS1083 Week 2: Arrays, ArrayList

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

Inf1-OOP. Encapsulation and Collections. Perdita Stevens, adapting earlier version by Ewan Klein. March 2, School of Informatics

Inf1-OOP. Encapsulation. Object Oriented Programming. Encapsulation Accessing Data Immutability. Encapsulation and Collections.

CS 106A, Lecture 27 Final Exam Review 1

After the code has executed, what is the capacity of list? What is its size? c

Introduction to Programming Using Java (98-388)

ArrayLists. Readings and References. Collections in the Real World. How can we manage lists of objects? Reading. Other References

ArrayLists. CSE 142, Summer 2002 Computer Programming 1.

All answers will be posted on web site, and most will be reviewed in class.

CS 211: Using ArrayList, Implementing Arraylist

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Binghamton University. CS-140 Fall Chapter 7.7. Lists. Java Library Data Structures

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

Lecture 6: ArrayList Implementation

Grouping Objects (I)

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

Use of the ArrayList class

Objects and Iterators

CSE 143 Lecture 4. Preconditions

What happens if someone new wants to join our awesome club?

Inheritance and Interfaces

CS 106A, Lecture 27 Final Exam Review 1

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

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

CMSC 132: Object-Oriented Programming II

Arrays and ArrayLists. David Greenstein Monta Vista High School

CSC 222: Object-Oriented Programming. Fall 2017

Flowcharts [15 points]

Grouping objects Lecture 7

CS Introduction to Data Structures Week 1 Thursday

CITS1001 week 6 Libraries

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

Building Java Programs

Big O & ArrayList Fall 2018 Margaret Reid-Miller

Lesson 2.4 Arraylist

CSC 222: Object-Oriented Programming. Spring 2012

CS 106A, Lecture 19 ArrayLists

Parsing JSON, Using Libraries, Java Collections, Generics. Slides adapted from Craig Zilles

Dynamic Data Structures and Generics

COMP-202. Generics. COMP Generics, 2013 Jörg Kienzle and others

Last Week: Organizing Data. Last Week: Parallel Arrays. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Examination Questions Midterm 1

CS S-08 Arrays and Midterm Review 1

Assignment 6 YEAH Hours. Ben Barnett and Avery Wang

CMSC 132: Object-Oriented Programming II. Generic Programming. Department of Computer Science University of Maryland, College Park

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

CSC Java Programming, Fall Java Data Types and Control Constructs

Parsing JSON, Using Libraries, Java Collections, Generics

Building Java Programs

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS 314 Exam 1 Spring 2018

CMSC 132: Object-Oriented Programming II

Inheritance. Improving Structure with Inheritance. Dr. Siobhán Drohan Mairead Meagher. Produced by:

CSE 8B Intro to CS: Java

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

1. ArrayList and Iterator in Java

Array Lists. CSE 1310 Introduction to Computers and Programming University of Texas at Arlington. Last modified: 4/17/18

Garbage Collection (1)

Unit5: Packages and abstraction

CHAPTER 15 MORE STANDARD JAVA TYPES

1.00/ Lecture 8. Arrays-1

CSC 222: Object-Oriented Programming. Fall Object-oriented design

AP Computer Science A

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

COMP More About Arrays. Yi Hong June 05, 2015

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

Transcription:

ArrayLists COMP1400 Week 8

Working with arrays There are a number of common actions we want to do with arrays: adding and deleting copying looking for a particular element counting the elements

Arrays Arrays are intrinsically fixed-length storage. Adding or deleting elements from arrays is cumbersome: create a new larger/smaller array copy the unaffected elements add/remove the affected element

Abstraction Rather than rewriting methods that perform these actions every time we use an array, we should abstract them into a new object. What we want is a new class that implements a variable-length list. The public interface should provide methods to implement the actions listed above.

ArrayList The ArrayList class in the Java Class Library provides this capability. http://docs.oracle.com/javase/1.5.0/docs/api/ java/util/arraylist.html

Encapsulation The ArrayList class abstracts and encapsulates all the methods for implementing a variable-length list using fixed-length arrays. ArrayList<String> private String[] mylist; public void add(string s); public String get(int pos);

Generic classes Each ArrayList holds a specific type (or class) of object. This class is given as a type parameter in angle brackets <> after the name. The type of the methods get, set and add depend on the given type. Parameterised types are called generic classes.

Type parameters When we create a variable that holds an ArrayList we also need to provide the type of objects it contains: ArrayList<String> listofstrings; ArrayList<Integer> listofints; ArrayList<Book> listofbooks; These are called the type parameters.

Type parameters When we create a variable that holds an collection ArrayList class we also need to provide the type of objects it contains: ArrayList<String> listofstrings; ArrayList<Integer> listofints; ArrayList<Book> listofbooks; These are called the type parameters.

Type parameters When we create a variable that holds an collection item ArrayList class we also need class to provide the type of objects it contains: ArrayList<String> listofstrings; ArrayList<Integer> listofints; ArrayList<Book> listofbooks; These are called the type parameters.

Type parameters When we create a variable that holds an collection item ArrayList class we also need class to provide the type of objects it contains: ArrayList<String> listofstrings; ArrayList<Integer> listofints; ArrayList<Book> listofbooks; These are called the type parameters. angle brackets

List of Strings ArrayList<String> classroll = new ArrayList<String>(); classroll.add("sim Mautner"); String who = classroll.get(0); // who is now Sim Mautner

List of ints This does not work: ArrayList<int> scores = new ArrayList<int>(); scores.add(1); int s = scores.get(0); The type parameter must be a class not a primitive type.

List of ints Instead we use: ArrayList<Integer> scores = new ArrayList<Integer>(); scores.add(1); int s = scores.get(0); The Integer class is an object-wrapper for the primitive type int.

Wrapper Classes Java implements wrapper classes to convert primitive types into objects automatically. Integer intobject = 1; Double doubleobject = 2.0; Boolean boolobject = true; Character charobject = x ;

Importing Since ArrayLists are part of the JCL, we must first import them before use: import java.util.arraylist;

Construction To construct an ArrayList we will usually use the simple no-parameter constructor: size 0 // create an empty list ArrayList<String> classroll = new ArrayList<String>(); There are two other constructors but we won t be using them much.

Adding items A newly constructed list is empty. We can add items using the add method. classroll.add("malcolm"); classroll.add("claude"); The type of objects we add must match the type parameter. size 0 1 2 Malcolm Claude classroll.add(47); // ERROR

Adding duplicates We can add something to a list more than once. classroll.add("malcolm"); classroll.add("malcolm"); size 0 4 Malcolm 1 2 3 Claude Malcolm Malcolm

Size We can use the size method to access the number of objects on the list: int nstudents = classroll.size(); // nstudents == 2 classroll.add("sim"); size 0 1 2 Malcolm Claude nstudents = classroll.size(); // nstudents == 3

Size We can use the size method to access the number of objects on the list: int nstudents = classroll.size(); // nstudents == 2 classroll.add("sim"); size 0 1 23 Malcolm Claude nstudents = classroll.size(); // nstudents == 3 2 Sim

Get We can access elements on the list by their index using the get method. String me = classroll.get(0); // me == "Malcolm" String him = classroll.get(1); // him == "Claude"

Indexing Note that the indices always start from 0 and end at size-1. classroll.size(); // returns 3 classroll.get(0); // returns "Malcolm" classroll.get(2); // returns "Sim" size 0 1 2 3 Malcolm Claude Sim classroll.get(3); // ERROR

Remove We can use the remove method to remove the element at a given index. The other elements get renumbered. classroll.remove(1); size 0 3 Malcolm classroll.size(); // returns 2 1 2 Claude Sim classroll.get(1); // "Sim"

Remove We can use the remove method to remove the element at a given index. The other elements get renumbered. classroll.remove(1); size 0 2 Malcolm classroll.size(); // returns 2 1 Sim classroll.get(1); // "Sim"

Copying There is a special constructor for creating a copy of a list: ArrayList<String> copy = new ArrayList<String>( classroll); size 0 1 32 Malcolm Claude Sim copy.add("troy");

Copying There is a special constructor for creating a copy of a list: ArrayList<String> copy = new ArrayList<String>( classroll); size 0 1 32 Malcolm Claude Sim copy.add("troy"); size 0 1 2 Malcolm Sim

Copying There is a special constructor for creating a copy of a list: ArrayList<String> copy = new ArrayList<String>( classroll); size 0 1 32 Malcolm Claude Sim copy.add("troy"); size 0 1 2 3 Malcolm Sim Troy

Other methods There are other methods you can read about in the API documentation: clear - remove all elements set - set value of a given element insert - insert an element at an index contains - test if an element is on the list

For-each loop A for-each loop is used to iterate over all the elements of a collection: for (String who : classroll) { // action performed on // each element System.out.println(who); }

For-each loop element A for-each type loop is used to iterate over all the elements of a collection: for (String who : classroll) { // action performed on // each element System.out.println(who); }

For-each loop element element A for-each type variable loop is used to iterate over all the elements of a collection: for (String who : classroll) { // action performed on // each element System.out.println(who); }

For-each loop element element list A for-each type variable variable loop is used to iterate over all the elements of a collection: for (String who : classroll) { // action performed on // each element System.out.println(who); }

Arrays vs ArrayLists // declaring array variables String[] arrayofstrings; int[] arrayofints; // declaring list variables ArrayList<String> listofstrings; ArrayList<Integer> listofints;

Arrays vs ArrayLists // constructing arrays arrayofstrings = new String[5] arrayofints = new int[10] // constructing lists (empty) listofstrings = new ArrayList<String>(); listofints = new ArrayList<Integer>();

Arrays vs ArrayLists // measuring size int arraysize = arrayofstrings.length; int listsize = listofstrings.size();

Arrays vs ArrayLists // getting elements String s1 = arrayofstrings[2]; int i1 = arrayofints[1]; String s2 = listofstrings.get(2); int i2 = listofints.get(1);

Arrays vs ArrayLists // setting elements arrayofstrings[2] = "Malcolm"; arrayofints[1] = 40; listofstrings.set(2, "Malcolm"); listofints.set(1, 40);

Arrays vs ArrayLists // iterating for (int i = 0; i < arrayofstrings.length; i++) { // process arrayofstrings[i] } foreach (String s : listofstrings) { // process s }

Arrays vs ArrayLists // Copying String[] copyarray = new String[arrayOfStrings.length+1]; for (int i = 0; i < arrayofstrings.length; i++) { copyarray[i] = arrayofstrings[i]; } ArrayList<String> copylist = new ArrayList<String>(listOfStrings);

Arrays vs ArrayLists // Adding an element String[] copyarray = new String[arrayOfStrings.length+1]; for (int i = 0; i < arrayofstrings.length; i++) { copyarray[i] = arrayofstrings[i]; } copy[arrayofstrings.length] = value; arrayofstrings = copyarray; listofstrings.add(value);

Other collections Sets (unordered, no duplicates): http://docs.oracle.com/javase/1.5.0/docs/api/ java/util/hashset.html Maps (look-up tables with key/value pairs): http://docs.oracle.com/javase/1.5.0/docs/api/ java/util/hashmap.html