Java Coding 6. Collections

Similar documents
Chapter 6 Arrays and Array Lists

Chapter Goals. T To understand the concept of regression testing. Chapter 6 Arrays and Array Lists. Arrays Array: Sequence of values of the same type

ARRAYS and ARRAYLISTS

CS 302: Introduction to Programming in Java. Lecture 12

Big O & ArrayList Fall 2018 Margaret Reid-Miller

AP Computer Science Lists The Array type

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

Arrays and Array Lists

Chapter 8. Arrays and Array Lists. Chapter Goals. Chapter Goals. Arrays. Arrays. Arrays

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

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

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

Chapter Seven: Arrays and Array Lists. Chapter Goals

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

Dynamic Arrays. Fundamentals of Computer Science

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

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

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

Dynamically sized arrays

Java Coding 3. Over & over again!

Garbage Collection (1)

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington

Lists using ArrayList

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

Using arrays to store data

STUDENT LESSON A15 ArrayList

Flowcharts [15 points]

ArrayLists. Chapter 12.1 in Savitch

CS1083 Week 2: Arrays, ArrayList

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

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

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

H212 Introduction to Software Systems Honors

Week 4, Wednesday (Spring 2015). Dr. Yoder. Sec 051. Page 1 of 5

4CCS1PRP, Programming Practice 2012 Lecture 6: Arrays - Part 1

Slides are adapted from the originals available at

CSC 222: Object-Oriented Programming. Spring 2012

CS Programming I: ArrayList

Interfaces, collections and comparisons

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

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

Lab Activity Plan. John Dalbey CPE /30/2013

ArrayList; Names example

Chapter 7: Arrays and the ArrayList Class

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

ENGR 2710U Midterm Exam UOIT SOLUTION SHEET

Arrays and ArrayLists. David Greenstein Monta Vista High School

Intro to Computer Science II

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

String. Other languages that implement strings as character arrays

Objektorienterad programmering

Advanced Java Concepts Unit 2: Linked Lists.

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

The Scanner class reads data entered by the user. Methods: COSC Dr. Ramon Lawrence. Page 3. COSC Dr. Ramon Lawrence A) A = 6, B = 3

Methods. Every Java application must have a main method.

Arrays. Eng. Mohammed Abdualal

COMP 202. Programming With Arrays

Controls Structure for Repetition

CompSci 125 Lecture 11

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Introduction to Computer Science I

CS 170, Section /3/2009 CS170, Section 000, Fall

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

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

1.00 Tutorial 3. Methods, Classes Arrays & ArrayLists. September 26 & 27, 2005

Lists using LinkedList

1.00/ Lecture 8. Arrays-1

CS111: PROGRAMMING LANGUAGE II

COMP-202: Foundations of Programming. Lecture 11: ArrayList, and Linked List Sandeep Manjanna, Summer 2015

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

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Collections and Maps

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

STUDENT LESSON A12 Iterations

CS111: PROGRAMMING LANGUAGE II

CS 200 Objects and ArrayList Jim Williams, PhD

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Assignment 8B SOLUTIONS

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Last Class. While loops Infinite loops Loop counters Iterations

1.00 Lecture 9. Arrays

Chapter Goals. Contents LOOPS

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

Learn more about our research, discover data science, and find other great resources at:

Computational Expression

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Example: Monte Carlo Simulation 1

Lesson 26: ArrayList (W08D1)

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

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Arrays. CSE 142, Summer 2002 Computer Programming 1.

Introduction to Functional Programming in Java 8

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

AP Programming - Chapter 13 Lecture page 1 of 17

1. What is the difference between a compiler and an interpreter? Also, discuss Java s method.

1.00/ Lecture 8. Arrays-1

CSC 222: Object-Oriented Programming. Fall 2017

Transcription:

Java Coding 6 Collections

Arrays of Objects

Arrays of objects Array contains only references to objects Track[] tracks; tracks = new Track[5]; Still need to create actual objects tracks[0] = new Track( David, 100); tracks[1] = new Track( Gunes, 200); tracks 0 David 100 1 2 3 4 Gunes 200 tracks[0].gettitle() tracks[4].gettitle()

Make Parallel Arrays into Arrays of Objects Don't do this int[] accountnumbers; double[] balances; Don't use parallel arrays Figure 4

Make Parallel Arrays into Arrays of Objects Avoid parallel arrays by changing them into arrays of objects: BankAccount[] accounts; Figure 5

ArraysofObjects - Example Date class Properties: day, month, year Constructors: copy constructor and others Methods: get methods, clone, equals, compareto, tostring Main method Create an array to keep date objects Ask the user to enter date objects until a sentinel value Print the contents of the array Hints: Make sure array has space Keep the number of objects in the array, etc.

Inner class Example - MusicCD Class MusicCD( title, artist, tracks) String gettitle() String getartist() Track gettrack(int) int getduration() Date getreleasedate() String title String Artist Date releasedate??? tracks collection of Date( String) String tostring() int year int month int day Track( title, length) String gettitle() int getlength() String title int length

Array Lists An array list stores a sequence of values whose size can change. An array list can grow and shrink as needed. ArrayList class supplies methods for many common tasks, such as inserting and removing elements. An array list expands to hold as many elements as needed. Copyright 2014 by John Wiley & Sons. All rights reserved. 8

Syntax 6.4 Array Lists Copyright 2014 by John Wiley & Sons. All rights reserved. 10

Declaring and Using Array Lists To declare an array list of strings ArrayList<String> names = new ArrayList<String>(); To use an array list import java.util.arraylist; ArrayList is a generic class Angle brackets denote a type parameter Replace String with any other class to get a different array list type Copyright 2014 by John Wiley & Sons. All rights reserved. 11

Declaring and Using Array Lists ArrayList<String> is first constructed, it has size 0 Use the add method to add an object to the end of the array list: names.add("emily"); // Now names has size 1 and element "Emily names.add("bob"); // Now names has size 2 and elements "Emily", "Bob names.add("cindy"); // names has size 3 and elements "Emily", "Bob", // and "Cindy The size method gives the current size of the array list. Size is now 3 Figure 17 Adding an Array List Element with add Copyright 2014 by John Wiley & Sons. All rights reserved. 12

Declaring and Using Array Lists To obtain an array list element, use the get method Index starts at 0 To retrieve the name with index 2: String name = names.get(2); // Gets the third element // of the array list The last valid index is names.size() - 1 A common bounds error: int i = names.size(); name = names.get(i); // Error To set an array list element to a new value, use the set method: names.set(2, "Carolyn"); Copyright 2014 by John Wiley & Sons. All rights reserved. 13

Declaring and Using Array Lists An array list has methods for adding and removing elements in the middle. This statement adds a new element at position 1 and moves all elements with index 1 or larger by one position. names.add(1, "Ann"); Copyright 2014 by John Wiley & Sons. All rights reserved. 14

Declaring and Using Array Lists The remove method, removes the element at a given position moves all elements after the removed element down by one position and reduces the size of the array list by 1. names.remove(1); To print an array list: System.out.println(names); // Prints [Emily, Bob, Carolyn] Copyright 2014 by John Wiley & Sons. All rights reserved. 15

Declaring and Using Array Lists Figure 18 Adding and Removing Elements in the Middle of an Array List Copyright 2014 by John Wiley & Sons. All rights reserved. 16

Using the Enhanced for Loop with Array Lists You can use the enhanced for loop to visit all the elements of an array list ArrayList<String> names =... ; for (String name : names) { } System.out.println(name); This is equivalent to: for (int i = 0; i < names.size(); i++) { } String name = names.get(i); System.out.println(name); Copyright 2014 by John Wiley & Sons. All rights reserved. 17

Copying Array Lists Copying an array list reference yields two references to the same array list. After the code below is executed Both names and friends reference the same array list to which the string "Harry" was added. ArrayList<String> friends = names; friends.add("harry"); Figure 19 Copying an Array List Reference Copyright 2014 by John Wiley & Sons. All rights reserved. 18

Copying Array Lists To make a copy of an array list: construct the copy and pass the original list into the constructor: ArrayList<String> newnames = new ArrayList<String>(names); Copyright 2014 by John Wiley & Sons. All rights reserved. 19

Working With Array Lists Copyright 2014 by John Wiley & Sons. All rights reserved. 20

Wrapper Classes You cannot directly insert primitive type values into array lists. Like truffles that must be in a wrapper to be sold, a number must be placed in a wrapper to be stored in an array list. Use the matching wrapper class. Copyright 2014 by John Wiley & Sons. All rights reserved. 21

Wrapper Classes To collect double values in an array list, you use an ArrayList<Double>. If you assign a double value to a Double variable, the number is automatically put into a box Called auto-boxing: Automatic conversion between primitive types and the corresponding wrapper classes: Double wrapper = 29.95; Wrapper values are automatically unboxed to primitive types double x = wrapper; Figure 20 A Wrapper Class Variable Copyright 2014 by John Wiley & Sons. All rights reserved. 22

Self Check 6.35 Declare an array list primes of integers that contains the first five prime numbers (2, 3, 5, 7, and 11). Answer: ArrayList<Integer> primes = new ArrayList<Integer>(); primes.add(2); primes.add(3); primes.add(5); primes.add(7); primes.add(11); Copyright 2014 by John Wiley & Sons. All rights reserved. 23

Self Check 6.36 Given the array list primes declared in Self Check 35, write a loop to print its elements in reverse order, starting with the last element. Answer: for (int i = primes.size() - 1; i >= 0; i--) { System.out.println(primes.get(i)); } Copyright 2014 by John Wiley & Sons. All rights reserved. 24

Self Check 6.37 What does the array list names contain after the following statements? ArrayList<String> names = new ArrayList<String>; names.add("bob"); names.add(0, "Ann"); names.remove(1); names.add("cal"); Answer: "Ann", "Cal" Copyright 2014 by John Wiley & Sons. All rights reserved. 25

Self Check 6.39 Consider this method that appends the elements of one array list to another: public void append(arraylist<string> target, ArrayList<String> source) { for (int i = 0; i < source.size(); i++) { target.add(source.get(i)); } } What are the contents of names1 and names2 after these statements? ArrayList<String> names1 = new ArrayList<String>(); names1.add("emily"); names1.add("bob"); names1.add("cindy"); ArrayList<String> names2 = new ArrayList<String>(); names2.add("dave"); append(names1, names2); Continu ed Copyright 2014 by John Wiley & Sons. All rights reserved. 26

Self Check 6.39 Answer: names1 contains "Emily", "Bob", "Cindy", "Dave"; names2 contains "Dave" Copyright 2014 by John Wiley & Sons. All rights reserved. 27

ArrayListPlay - Play with collections of Date objects

indexof and contains public int indexof(object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element More formally, returns the lowest index i such that (o==null? get(i)==null : o.equals(get(i))), or -1 if there is no such index public Boolean contains(object o) Returns true if this list contains the specified element More formally, returns true if and only if this list contains at least one element e such that (o==null? e==null : o.equals(e)).

Easy Problem Read in a set of positive integer values and then print out a table showing the average, each of the values and their difference from the average. Umm must remember all the values we read in in order to print the table. Could use ArrayList BUT integers are not Objects! (use Integer wrapper class) Example output Average is 5 Value Diff -------------- 10 5 3-2 6 1 1-4 --------------

Easy Problem Algorithm 1. read set of values (how? Fixed number, e.g. 4, ask user how many?, use sentinel?) 2. compute average of set of values (divide by zero error?) 3. print table using average & set of values Cannot directly store primitive types in ArrayList + solution create own wrapper class, MyInt + use Java s wrapper classes Integer, Double, etc. + utilise autoboxing/unboxing. Java s wrapper classes have other useful methods, e.g. valueof to convert string to int or double.

Example Write a program that Reads a sequence of values and Prints them, marking the largest value

section_7/largestinarraylist.java 1 import java.util.arraylist; 2 import java.util.scanner; 3 4 /** 5 This program reads a sequence of values and prints them, marking the largest value. 6 */ 7 public class LargestInArrayList 8 { 9 public static void main(string[] args) 10 { 11 ArrayList<Double> values = new ArrayList<Double>(); 12 13 // Read inputs 14 15 System.out.println("Please enter values, Q to quit:"); 16 Scanner in = new Scanner(System.in); 17 while (in.hasnextdouble()) 18 { 19 values.add(in.nextdouble()); 20 } 21 Continued Copyright 2014 by John Wiley & Sons. All rights reserved. 33

section_7/largestinarraylist.java 22 // Find the largest value 23 24 double largest = values.get(0); 25 for (int i = 1; i < values.size(); i++) 26 { 27 if (values.get(i) > largest) 28 { 29 largest = values.get(i); 30 } 31 } 32 33 // Print all values, marking the largest 34 35 for (double element : values) 36 { 37 System.out.print(element); 38 if (element == largest) 39 { 40 System.out.print(" <== largest value"); 41 } 42 System.out.println(); 43 } 44 } 45 } Continued Copyright 2014 by John Wiley & Sons. All rights reserved. 34

section_7/largestinarraylist.java Program Run Please enter values, Q to quit: 35 80 115 44.5 Q 35 80 115 <== largest value 44.5 Copyright 2014 by John Wiley & Sons. All rights reserved. 35

Using Array Algorithms with Array Lists The array algorithms can be converted to array lists simply by using the array list methods instead of the array syntax. Code to find the largest element in an array: double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } } Code to find the largest element in an array list: double largest = values.get(0); for (int i = 1; i < values.size(); i++) { if (values.get(i) > largest) { largest = values.get(i); } } Copyright 2014 by John Wiley & Sons. All rights reserved. 36

Storing Input Values in an Array List To collect an unknown number of inputs, array lists are much easier to use than arrays. Simply read the inputs and add them to an array list: ArrayList<Double> inputs = new ArrayList<Double>(); while (in.hasnextdouble()) { } inputs.add(in.nextdouble()); Copyright 2014 by John Wiley & Sons. All rights reserved. 37

Removing Matches To remove elements from an array list, call the remove method. ArrayList<String> words =...; for (int i = 0; i < words.size(); i++) { String word = words.get(i); if (word.length() < 4) { Remove the element at index i. } } Error: skips the element after the moved element Copyright 2014 by John Wiley & Sons. All rights reserved. 38

Removing Matches Should not increment i when an element is removed Pseudocode If the element at index i matches the condition Remove the element. Else Increment i. Copyright 2014 by John Wiley & Sons. All rights reserved. 39

Removing Matches Use a while loop, not a for loop int i = 0; while (i < words.size()) { String word = words.get(i); if (word.length() < 4) { words.remove(i); } else { i++; } } Copyright 2014 by John Wiley & Sons. All rights reserved. 40

Choosing Between Array Lists and Arrays For most programming tasks, array lists are easier to use than arrays Array lists can grow and shrink. Arrays have a nicer syntax. Recommendations If the size of a collection never changes, use an array. If you collect a long sequence of primitive type values and you are concerned about efficiency, use an array. Otherwise, use an array list. Copyright 2014 by John Wiley & Sons. All rights reserved. 41

Choosing Between Array Lists and Arrays Copyright 2014 by John Wiley & Sons. All rights reserved. 42