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

Similar documents
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

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.

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

CS 302: Introduction to Programming in Java. Lecture 12

Introduction to Computer Science I

CS 211: Using ArrayList, Implementing Arraylist

Java Coding 6. Collections

CS 211: Using ArrayList, Implementing Arraylist

Computational Expression

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

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

CS Programming I: ArrayList

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

Arrays. CSE 142, Summer 2002 Computer Programming 1.

ArrayLists. Chapter 12.1 in Savitch

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

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

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

Building Java Programs

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

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12

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

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

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

CITS1001 week 6 Libraries

Interfaces, collections and comparisons

Working with arrays. ArrayLists. Abstraction. Arrays

Using arrays to store data

Building Java Programs

CS 106A, Lecture 19 ArrayLists

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

Big O & ArrayList Fall 2018 Margaret Reid-Miller

CS 106A, Lecture 20 ArrayLists and HashMaps

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

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

Arrays and ArrayLists. David Greenstein Monta Vista High School

Computer Science 210 Data Structures Siena College Fall 2018

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

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

CITS1001 week 4 Grouping objects

Lecture 6: ArrayList Implementation

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

AP Computer Science. ArrayLists

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

CSE 8B Intro to CS: Java

STUDENT LESSON A15 ArrayList

Arrays and Array Lists

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

ARRAYS and ARRAYLISTS

CMPT 126: Lecture 11 Collections: Abstract Data Types and Dynamic Representation (Chapt. 12)

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

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

+ Abstract Data Types

Advanced Java Concepts Unit 2: Linked Lists.

1007 Imperative Programming Part II

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

Lists using ArrayList

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

Collections of Objects. Object Oriented Programming Camilo López

Lesson 26: ArrayList (W08D1)

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

Garbage Collection (1)

ArrayList. Introduction. java.util.arraylist

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

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

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

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

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

Chapter Seven: Arrays and Array Lists. Chapter Goals

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

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

Generics. IRS W-9 Form

Dynamically sized arrays

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

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

Programming with Java

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

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

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

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

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

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

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

CSE 143 Lecture 4. Preconditions

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

Flowcharts [15 points]

AP Programming - Chapter 13 Lecture page 1 of 17

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

JAVA WRAPPER CLASSES

Principles of Computer Science

Full file at

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.

Formatting Output & Enumerated Types & Wrapper Classes

Java Collections Framework

CS112 Lecture: Primitive Types, Operators, Strings

Lesson 2.4 Arraylist

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

Transcription:

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

Rigidity of arrays 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.

ArrayList 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.

ArrayList: Methods 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); Output [hip, hip, hooray]

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"]

ArrayList: More methods contains() boolean iship = cheers.contains("hip"); // iship is true remove() cheers.remove("hip"); // removes first occurrence of "hip" Elements of cheers: "hop", "hip", "hooray" get(int index) cheers.get(0); // get the first element // returns "hop"

ArrayList and Loops Looping over ArrayList: Standard for loop for (int i = 0; i < cheers.size(); i++) { System.out.println(cheers.get(i)); }

ArrayList and Loops Looping over ArrayList: Standard for loop for (int i = 0; i < cheers.size(); i++) { System.out.println(cheers.get(i)); } 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)); } Output 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);

Auto-boxing, contrast Automatic vs explicit conversion between primitive types and corresponding wrapper classes. Auto-box example ArrayList<Double> data = new ArrayList<Double>(); data.add(29.95); double x = data.get(0); Contrast... data.add(double.valueof(29.95)); Double tmp = data.get(0); double x = tmp.doublevalue(); Using Double class methods: double doublevalue() Return double value of object. Double valueof(double d) Return Double value of specified double.

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 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

More ArrayList Goodies Sorting an arraylist, vs sorting an array. Multiple ways, e.g, Array import java.util.arrays;... int[] mynums = new int[] {1, 3, 7, 5, 10}; Arrays.sort(myNums); System.out.println(Arrays.toString(myNums)); //[1, 3, 5, 7, 10] ArrayList import java.util.arraylist; import java.util.collections;... ArrayList mynums<integer> = new ArrayList<Integer>(); mynums.add(1); mynums.add(5); mynums.add(3); Collections.sort(myNums); System.out.println(myNums); //[1, 3, 5]

More ArrayList Goodies Convert between Array and Arraylist Array to ArrayList import java.util.collections; import java.util.arraylist;... Integer[] mynums = new Integer[] {1, 3, 7, 5, 10}; ArrayList<Integer> mynums2 = new ArrayList<Integer>(); Collections.addAll(myNums2,myNums); System.out.println(myNums2); //[1, 3, 7, 5, 10]; ArrayList to Array... Integer[] mynums3 = mynums2.toarray(new Integer[myNums2.size()]) System.out.println(Arrays.toString(myNums)); //[1,3,7,5,10]

Java API Look at sample Javadoc web page. http://docs.oracle.com/javase/8/docs/api/

Java API: Top Node

Java API: Entry for ArrayList

Maps

Associative Arrays 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.

Map People to their Matric Nos. Keys Peter Michael Helen Mary John Values s0189034 s0289125 s0378435 s0412375 s0456782

Map Words to Length Keys Values "this" "is" "the" 4 2 3 "time" "and"

Map People to their Matric Nos: Wrong! Keys Peter Michael Peter Mary John Values s0189034 s0289125 s0378435 s0412375 s0456782 NB Keys must be unique.

Map People to their Telephone Nos: Wrong! Keys Peter Michael Helen Mary John Values 504455 502331 509800 506666 501235 A given key can only be mapped to one value. However, type of value can be array, or some other object.

HashMap Import HashMap import java.util.hashmap;

HashMap Import HashMap import java.util.hashmap; Declare HashMap HashMap<String, Integer> map = new HashMap<String, Integer>(); HashMap takes two type parameters. Here, String is type of key, Integer is type of value.

Mapping Words to their Lengths 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 String sent = "this is the time and this is the record of the ti String[] words = sent.split(" "); // split on whitespace

HashMap: Add and retrieve mappings 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. int wl = wordlengths.get("record"); // value is 6

HashMap: Add and retrieve mappings wordlengths.keyset(): the set of keys in wordlengths. [of, record, time, is, the, this, and] wordlengths.values(): the collection of values in wordlengths. [2, 6, 4, 2, 3, 4, 3]

HashMap: Add and retrieve mappings wordlengths.keyset(): the set of keys in wordlengths. [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)); } Output of => 2 record => 6 time => 4 is => 2 the => 3 this => 4

HashMap: Printing Output System.out.println(wordLengths); Output {of=2, record=6, time=4, is=2, the=3, this=4, and=3} Format is {Key1 =Value1, Key2 =Value2,... }

HashMap: More methods Check if a key is present? boolean b = wordlengths.containskey( Hello ); Remove a key value pair wordlengths.remove( and ); Check number of mappings present int s = wordlengths.size();

ArrayList & HashMap 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/

Reading 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.