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

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

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

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.

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

Introduction to Computer Science I

CS 302: Introduction to Programming in Java. Lecture 12

Java Coding 6. Collections

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

CS 211: Using ArrayList, Implementing Arraylist

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

Computational Expression

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

Arrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein

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

Inf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

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

CS 211: Using ArrayList, Implementing Arraylist

ArrayLists. Chapter 12.1 in Savitch

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics

Class Foo. instance variables. instance methods. Class FooTester. main {

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

COMP 111. Introduction to Computer Science and Object-Oriented Programming. Week 10

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

1B1a Arrays. Arrays. Indexing. Naming arrays. Why? Using indexing. 1B1a Lecture Slides. Copyright 2003, Graham Roberts 1

Arrays and Array Lists

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

Inf1-OP. Inf1-OP Exam Review. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 16, School of Informatics

Using arrays to store data

Working with arrays. ArrayLists. Abstraction. Arrays

ARRAYS and ARRAYLISTS

Big O & ArrayList Fall 2018 Margaret Reid-Miller

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 2 EXAMINATIONS 2013/2014 CI101/CI101H. Programming

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

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12

Learning Outcomes for this week. Inf1-OP. A Foundation for Programming. A Foundation for Programming

+ Abstract Data Types

CITS1001 week 6 Libraries

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Interfaces, collections and comparisons

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

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics

Building Java Programs

Programming with Java

Garbage Collection (1)

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

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

Lecture 6: ArrayList Implementation

STUDENT LESSON A15 ArrayList

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

Chapter Seven: Arrays and Array Lists. Chapter Goals

CS Programming I: ArrayList

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Arrays and ArrayLists. David Greenstein Monta Vista High School

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

Building Java Programs

CS 106A, Lecture 19 ArrayLists

CS 106A, Lecture 20 ArrayLists and HashMaps

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

1007 Imperative Programming Part II

Lesson 2.4 Arraylist

Main loop structure. A Technical Support System. The exit condition. Main loop body

Section 2.2 Your First Program in Java: Printing a Line of Text

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

CSE 8B Intro to CS: Java

Computer Science 210 Data Structures Siena College Fall 2018

Dynamically sized arrays

Inf1-OP. Course Overview. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

Lists using ArrayList

Advanced Java Concepts Unit 2: Linked Lists.

MODULE 6q - Exceptions

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Arrays. CSE 142, Summer 2002 Computer Programming 1.

ArrayList. Introduction. java.util.arraylist

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

EXAM Computer Science 1 Part 1

Lesson 26: ArrayList (W08D1)

Formatting Output & Enumerated Types & Wrapper Classes

Section 2.2 Your First Program in Java: Printing a Line of Text

Inf1-OOP. Data Types. A Foundation for Programming. type value set operations. Overview. Using Data Types 1. Image Processing

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.

Processing/Java Syntax. Classes, objects, arrays, and ArrayLists

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

Collections of Objects. Object Oriented Programming Camilo López

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Review: Array Initializer Lists

Strings and Arrays. Hendrik Speleers

Java Overview An introduction to the Java Programming Language

Full file at

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

AP Computer Science Homework Set 1 Fundamentals

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

Inf1-OOP. Textbooks. Who and What. Organizational Issues. Why Java? Course Overview. Hello, World! in Java. Ewan Klein, Perdita Stevens

Inf1-OOP. Data Types. A Foundation for Programming. type value set operations. Overview. Using Data Types 1. Image Processing

Getting started with Java

Computational Expression

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

EECS168 Exam 3 Review

Transcription:

Rigidity of arrays Inf1-OP Collections Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics Length of array is fixed at creation time. Can t be expanded. Can t be shrunk. Arrays are part of Java language uses special syntax. E.g., myarray[i] for accessing the ith element. February 26, 2018 ArrayList ArrayList: Methods ArrayList: Can grow and shrink as needed; provides methods for inserting and removing elements. Declaration ArrayList<String> cheers = new ArrayList<String>(); This is an array list of strings; counterpart to String[]. Angle brackets indicate that String is a type parameter. Can replace String with e.g. HotelRoom to get different array list type. In general: use ArrayList<E> to collect objects of type E; but E cannot be a primitive type. A newly constructed ArrayList has size 0. ArrayList has various methods, which allow us to: keep on adding new elements; remove elements. The size changes after each addition / removal.

ArrayList: Adding Adding Elements ArrayList<String> cheers = new ArrayList<String>(); cheers.add("hip"); cheers.add("hip"); cheers.add("hooray"); int n = cheers.size(); // n gets value 3 add() appends each element to the end of the list. Printing an ArrayList System.out.println(cheers); ArrayList: More methods Index of first occurrence int ind = cheers.indexof("hip"); // ind gets value 0 Adding element at an index cheers.add(1, "hop"); // 2nd "hip" gets shunted along Elements of cheers: ["hip", "hop", "hip", "hooray"] [hip, hip, hooray] ArrayList: More methods contains() boolean iship = cheers.contains("hip"); // iship is true ArrayList and Loops Looping over ArrayList: Standard for loop remove() cheers.remove("hip"); // removes first occurrence of "hip" for (int i = 0; i < cheers.size(); i++) { System.out.println(cheers.get(i)); Elements of cheers: "hop", "hip", "hooray" get(int index) cheers.get(0); // get the first element // returns "hop" Enhanced for again for (String s : cheers) { System.out.println(s);

ArrayList and Loops Enhanced for again for (String s : cheers) { System.out.print(s + "\thas index: "); System.out.println(cheers.indexOf(s)); hop has index: 0 hip has index: 1 hooray has index: 2 Wrapper Classes Wrapper Classes: The type variable E in a generic type like ArrayList<E> must resolve to a reference type. So ArrayList<int> will not compile. All the primitive types can be turned into objects by using wrapper classes: Primitive Type boolean char double int long Wrapper Class Boolean Character Double Integer Long NB Wrapper class names are always capitalized, always complete words. Auto-boxing Conversion between primitive types and corresponding wrapper classes is automatic. Process of conversion is called auto-boxing Auto-box example Double batterycharge = 2.75; double x = batterycharge; Auto-box example ArrayList<Double> data = new ArrayList<Double>(); data.add(29.95); double x = data.get(0); Import Importing: To get full access to Java API, we need to import classes. Not necessary if class is in same folder, or part of java.lang (e.g., Math library). To use ArrayList, add the appropriate import statement at top of your file: Import example import java.util.arraylist; Import example Wrong! import java.util.arraylist<string>; // Don t use parameter

Java API Java API: Top Node Look at sample Javadoc web page. http://docs.oracle.com/javase/8/docs/api/ Java API: Entry for ArrayList Maps

Associative Arrays Map People to their Matric Nos. Associative array: Associates a collection of unique keys with values. Ordinary arrays: keys can only be integers. Associative arrays allow keys of many types, most notably strings. Examples: 1. Given a person s name, look up a telephone number. 2. Given an internet domain, look up its IP address. 3. Given a geo-location, look up its GPS coordinates. 4. Given a word, look up its frequency in a text. Relationship between key and value: mapping. Java: associative arrays are implemented by type HashMap. Michael Helen Mary John s0189034 s0289125 s0378435 s0412375 s0456782 Map Words to Length Map People to their Matric Nos: Wrong! "this" "is" "the" "time" "and" 4 2 3 Michael Mary John s0189034 s0289125 s0378435 s0412375 s0456782 NB must be unique.

Map People to their Telephone Nos: Wrong! HashMap Michael Helen Mary John 504455 502331 509800 506666 501235 Import HashMap import java.util.hashmap; Declare HashMap HashMap<String, Integer> map = new HashMap<String, Integer>(); A given key can only be mapped to one value. However, type of value can be array, or some other object. HashMap takes two type parameters. Here, String is type of key, Integer is type of value. Mapping Words to their Lengths HashMap: Add and retrieve mappings Goal: Given a string of words, derive an associative array that maps each word to its length. 1. Split the string on whitespace, to yield words. 2. For each word w, add it as a key, and associate it with value w.length(). 3. When we add the same key again, we overwrite the previous association wasteful but harmless in this case. split() method of String put(key, Value): put Value as the value of Key in wordlengths. HashMap<String, Integer> wordlengths = new HashMap<String, Integer>(); for (String word : words) { wordlengths.put(word, word.length()); add a key-value pair to the mapping get(key): get the value of Key in wordlengths. String sent = "this is the time and this is the record of the time"; String[] words = sent.split(" "); // split on whitespace int wl = wordlengths.get("record"); // value is 6

HashMap: Add and retrieve mappings wordlengths.keyset(): the set of keys in wordlengths. HashMap: Printing [of, record, time, is, the, this, and] Q How do we list all key-value pairs in a map? A Loop over the set of keys. for (String key : wordlengths.keyset()) { System.out.printf("%s => %s\n", key, wordlengths.get(key)); of => 2 record => 6 time => 4 is => 2 the => 3 this => 4 and => 3 ArrayList & HashMap System.out.println(wordLengths); {of=2, record=6, time=4, is=2, the=3, this=4, and=3 Format is {Key1 =Value1, Key2 =Value2,... Reading Use ArrayList when you want your arrays to be able to grow, or you want to easily insert and remove items in the middle of an array. Use HashMap when you want to use keys other than a predetermined list of integers. For more on ArrayList and HashMap, look at the Java API: http://docs.oracle.com/javase/8/docs/api/ Java Tutorial pp219-226, i.e. Chapter 7 Generics, stopping at Generic Methods. pp423-505, i.e. Chapter 12 Collections, stopping at Algorithms. In both cases, the book sections contain more material than we talked about. Remember the exam is open book! I don t expect you to remember all the different kinds of collections, but I do expect you to be able to look them up and use them.