Garbage Collection (1)

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

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

Big O & ArrayList Fall 2018 Margaret Reid-Miller

public static void main(string args[]){ arraylist(); recursion();

Example: Computing prime numbers

Introduction Data Structures

COMP-202 More Complex OOP

CSE143 Notes for Monday, 7/06/15

6.001 Notes: Section 15.1

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

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

Intro. Scheme Basics. scm> 5 5. scm>

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

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

+ Abstract Data Types

Collections, Maps and Generics

COMP-202 Unit 4: Programming with Iterations

Arrays. myints = new int[15];

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

COMP 202 Java in one week

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Chapter 1 Getting Started

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis

Topic 22 Hash Tables

Lesson 2.4 Arraylist

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

What did we talk about last time? Finished hunters and prey Class variables Constants Class constants Started Big Oh notation

Java Coding 6. Collections

Java Programming. Computer Science 112

Algorithms. Produced by. Eamonn de Leastar

Singly linked lists in C.

MITOCW watch?v=0jljzrnhwoi

INTRODUCTION TO DATA AND PROCEDURE

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

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we

Java Programming. Computer Science 112

Primitive vs Reference

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

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

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

Topic 10: The Java Collections Framework (and Iterators)

CITS1001 week 6 Libraries

ECE 122. Engineering Problem Solving Using Java

Data & Procedure Introduction

Introduction to Programming Using Java (98-388)

CITS1001 week 4 Grouping objects

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

Interfaces, collections and comparisons

COMP-202: Foundations of Programming. Lecture 16: Reference types Jackie Cheung, Winter 2016

Hi everyone. Starting this week I'm going to make a couple tweaks to how section is run. The first thing is that I'm going to go over all the slides

The Dynamic Typing Interlude

6.001 Notes: Section 1.1

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

MITOCW watch?v=kz7jjltq9r4

Outline. runtime of programs algorithm efficiency Big-O notation List interface Array lists

The following content is provided under a Creative Commons license. Your support

Super-Classes and sub-classes

CS108, Stanford Handout #8. Java Generics

Array Based Lists. Collections

MITOCW watch?v=flgjisf3l78

Lecture 7: Searching and Sorting Algorithms

6.001 Notes: Section 8.1

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

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

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

Warmup : Name that tune!

Last class. -More on polymorphism -super -Introduction to interfaces

Instructor: Craig Duckett. Lecture 04: Thursday, April 5, Relationships

STUDENT LESSON A15 ArrayList

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

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

CSE143 Notes for Monday, 4/25/11

Warm-Up: COMP Programming with Iterations 1

CSC 222: Object-Oriented Programming. Spring 2012

Warm up question. 2)Which of the following operators are defined on a half integer? Which of the following would it be useful to write as behaviors?

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

JAVA MOCK TEST JAVA MOCK TEST II

Slide 1 CS 170 Java Programming 1 The while Loop Duration: 00:00:60 Advance mode: Auto

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

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

Intro. Speed V Growth

CS102. Lecture 7. xkcd. xkcd. palindramas

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

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Post Experiment Interview Questions

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

CS 106A, Lecture 20 ArrayLists and HashMaps

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

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

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley

(Refer Slide Time 3:31)

Transcription:

Coming up: Today: Finish unit 6 (garbage collection) start ArrayList and other library objects Wednesday: Complete ArrayList, basics of error handling Friday complete error handling Next week: Recursion (Basics) + review 1

2

String int[] 3

Garbage Collection (1) When there are no more reference variables containing the address of an object, the object can no longer be accessed by the program It is useless, and therefore called garbage Java performs automatic garbage collection periodically When garbage collection occurs, all the memory allocated to store garbage objects is made available so it be allocated to store new objects 4

Garbage Collection (2) In other languages, the programmer has the responsibility for performing garbage collection Always ensure you do not lose the last reference to an object you still need 5

Garbage Collection (3) On the other hand, if you no longer need an object, you should make sure that none of your reference variables contain its address in memory You can do this by assigning null to the reference variables which contain the address of this object This is so that the memory it occupies can be reclaimed by the garbage collector and reused to store new objects 6

COMP-202 Unit 7: More Advanced OOP CONTENTS: ArrayList HashSet HashMap

Managing a big project Many times, you will need to use an Object type that someone else has created. For example, imagine if every time you wanted to store a sequence of symbols, you needed to use a char[] instead of String That would be awful... 8

Using Library Objects It's great to do things yourself when you can. However, at some point, for practical reasons, you have a desire to avoid reinventing the wheel There are many library methods that allow us to perform certain functions that are common. There are also many library Object types that allow us to represent certain data types without having to define the data type ourselves. 9

Benefits of using library objects 1)It makes your life easier. This is really the only benefit of using the library Objects, but it's a huge benefit. a)saves you the time of writing b)saves you the time of testing c)library objects have (usually) been designed well. 10

Downsides of using library objects A bit more initial overhead to understand. You have to learn HOW to use them. 11

Like taking the subway... 12

Lost in NY 13

You have to invest the time In theory, it's fastest to skip trying to understand the library Object. In fact, in many cases, the first time, it's slower to understand. If you use the library Object, you can sometimes misuse it. 14

You have to invest the time However, once you take the time to understand it, you're glad it's there. It's good to avoid reinventing the wheel 15

Part 1: ArrayList

Storing multiple data values of the same type We have seen that we can use an array (build in) when we need to store multiple data values of the same type. 17

Built in arrays Arrays are often ANNOYING to use! -Can't resize them -Have to worry about array index out of bounds values -Difficult to delete (have to shift everything over -Difficult to add elements -Just a head ache sometimes! 18

ArrayList There is an answer to all your problems! It is called ArrayList. 19

Driving a Car When you drive a car, you do not need to think about how the engine works. If you did, it would be bad. All you have to do is hit the gas and the brake, and turn the wheel at appropriate times. This is known as abstracting the notion of driving the car 20

Different levels of control Some Objects will give us more or less control and be different levels of abstraction. For example, in a manual transmission, you need know more about how the engine works than in an automatic. Our goal in using these library Objects is to have a simpler abstraction. 21

ArrayList An ArrayList in Java is a type defined to represent the NOTION of an array, but so that you don't have to think about the details of how an array works. It has all the functionality of a regular array, but it is much simpler to do things like add, delete, check if a value exists, etc 22

ArrayList of what? In Java, there is a notion of generics Consider the following 2 problems: 1)Given a String[] and a String, find the first index of the String[] that the String occurs 2)Given an int[] and an int, find the first index of the int[] that the int occurs 23

Find in String[] public static int findindex(string[] array, String target) { for (int i=0; i < array.length; i++) { if (array[i].equals(target)) { return i; } } return -1; } 24

Find in int[] public static int findindex(int[] array, int target) { for (int i=0; i < array.length; i++) { if (array[i] == target) { return i; } } return -1; } 25

ArrayList of what? Notice that there are only 2 differences: 1)The method header has String in one case and int in another case. 2)The if statement uses.equals in one case and == in the other case. In general, this method could be written for ANY type. #1 would be using the type name, #2 would use.equals if it's a reference and == if it's a primitive type 26

Cleverly designing ArrayList Since most array operations do not really involve the TYPE of the array, they only involve manipulating values inside the array, one can actually design an ArrayList to work on ANY type, using a notion known as generics We will not talk about how to define a type to be generic, but you should know how to use a generic type. 27

ArrayList of any reference type ArrayList is defined to work on ANY reference type. So I can create an ArrayList of String or an ArrayList of Scanner or an ArrayList of Pokemon This means that if you define your own type, you can create an ArrayList of it as well. Without this notion, the people who wrote ArrayList would have had to define their (almost identical) methods for every type they could think of (including predicting the future types that you would create!) 28

Using an ArrayList An ArrayList is an Object, thus you have to use the new keyword. You also have to tell Java what KIND of ArrayList to make. Remember, you can only make an ArrayList of reference types. Note: to do any of these, you will have to import java.util.arraylist; 29

Declare an ArrayList variable The syntax is a bit unusual: ArrayList<kind_of_thing> list; This declares a variable which has the type ArrayList of 'kind_of_thing' You will be able to store into this array list whatever the type 'kind_of_thing' is Before, we would have written this as: kind_of_thing[] list (for a simple array) 30

Creating an ArrayList object There is a constructor for ArrayList object that takes nothing as input: new ArrayList<kind_of_object>(); So for example: ArrayList<String> words = new ArrayList<String>(); This is the notion of creating and using a generic type 31

Using ArrayList Once you have this ArrayList class, you can use the methods provided in the class. To see the methods available, the best thing is to go to the documentation page: http://download.oracle.com/javase/6/docs/api/java/ut il/arraylist.html 32

Some common methods: Note: All methods are non-static. In the documentation, it will often refer to E as the type. This means it is the type that you defined your ArrayList to be of -add(e e) -add(int index, E element) -clear -get(int index) -indexof(object o) -remove(int index) -remove(object o) -size() 33

An ArrayList of names ArrayList<String> names = new ArrayList<String>(); names.add( Jon Stewart ); names.add( Stephen Colbert ); names.add( Samantha Bee ); names.add( John Oliver ); //now let's print the names: for (int i=0; i < names.size(); i++) { System.out.println(names.get(i)); } // Now he got his own show... names.remove( John Oliver ); 34

Comparison of FindWordsStartWithLetter public static String[] findwordsstartwithletter(string[] words, char c) public static ArrayList<String> findwordsstartwithletter(arraylist<string> words, char c) 35

Exercise Write a method that, given an ArrayList<String> returns a boolean representing whether the ArrayList is in alphabetical order. You may use the following methods: -get(int i), size() (defined on ArrayList) -compareto(string other) (defined to work on a String, returns -1 if this < other, +1 if this > other, 0 if equal) 36

Exercise public static boolean issorted(arraylist<string> words) { for (int i =0 ; i < words.size() 1; i++ ) { String prior = words.get(i); String subsequent = words.get(i + 1); if (prior.compareto(subsequent) > 0) { return false; } } return true; } 37

Reason regular arrays are still important Despite the ease of using ArrayList, it's still really really important to understand that underlying this nice data type called ArrayList, is an actual array. Why? Part of the reason is you understand what things are fast, and what are not. For example, you know that remove() will be a slow operation. Because it has to shift every value in the array over! 38

Be REALLY careful with references! ArrayList can ONLY be of a reference type. This means that in reality, the ArrayList is storing a list of links to actual Objects When you use the.get() method, you get a REFERENCE variable. This means you just get another link, but to the same Object. In this case, ALIASING is a potential problem. 39

Be REALLY careful with references! ArrayList<Point> points = new ArrayList<Point>(); points.add(new Point(1,1)); points.add(new Point(1,2)); Point first = points.get(0); //Now, in memory, I have 2 Objects //one represents the coordinate (1,1), the other represents (1,2) //However, both first AND points.get(0) are the same link... 40

Be REALLY careful with references! //continued first.setx(3); //What will the following print? System.out.println(points.get(0).getX()); 41

Be REALLY careful with references! //continued first.setx(3); //What will the following print? System.out.println(points.get(0).getX()); It will print 3. Because first was an alias here. So we have to be super careful! 42

One nice thing with String One good thing with an ArrayList of String is you do not need to worry about this. Remember that Strings are immutable meaning that you can't change a String once it's created. (You can change a String variable, but not the String object itself) This means that if you got a String as before, you could never change it. 43

Using final with references A related thing to be careful of is using the final keyword with references. Whenever you use the final keyword, you are saying that the value of the variable can not change. In the case of reference types, the value in a variable is an address. So the ADDRESS can't change. But the Object stored at that address CAN. 44

ArrayList with primitive types You can't use ArrayList with primitive types. This is a bit annoying because these are the most commonly used types. The solution: Wrapper classes 45

Wrapper classes Each of the primitive types have what is known as a Wrapper class. This is a reference type, that essentially consists of just one property---the primitive equivalent. It needs to have a way to store the primitive type and a way to get the primitive type back. 46

Ex: Integer Integer fiveasinteger = new Integer(5); int fiveasint = fiveasinteger.intvalue(); Now, since Integer is a reference type (all types other than the 8 primitive types are references), we can use it with an ArrayList 47

A guess as to the implementation public class Integer { private int value; public Integer(int original) { this.value = original; } } public int intvalue() { return this.value; } 48

Automatic unboxing In the latest version of Java, we also have this notion of automatic boxing and unboxing This means you can use Integer and int, for example, interchangably: Integer i = 3; //technically types don't match but this is OK This is an example where you create an object without using the new operator. (There are 3 : initializer lists, String literals, and wrapper classes) 49

Part 2: HashSet

Words Suppose that you have a list of English words. These words are not in any particular ordering. I ask you to tell me if a particular word exists in English or not. Would this be a fast or slow task? What if I told you that the list was sorted in alphabetical order? Would that make it a faster task? 51

Words Of course, knowing that a list is sorted makes it much easier. We can do something known as binary search. The idea here is we will start in approximately the middle and then only look at one half of our list, depending on if our target word is before or after. Whenever you look up a value in the dictionary, this is what you do. 52

HashSet There are some things that are great about ArrayList: 1)Very convenient 2)We already understand arrays, and these are very close to that. In some cases, however, if you don't care about the order that things are added to the list of things, they can be stored in a way that allows you to access values FASTER 53

HashSet In this case, there is a type you can use, similar to ArrayList, called HashSet. The main differences between HashSet and ArrayList: 1)HashSet is really fast to add, get, and remove values. This is because the order it keeps of the elements is sorted in a smart way. You don't know the exact order, but it's not always the same as its been inserted in. 2)As such, you can't do something like.get(index i). It wouldn't make sense. 54 3)In addition, you can't store the same value twice

HashSet HashSet<String> unique = new HashSet<String>(); unique.add( Jon Stewart ); unique.add( Stephen Colbert ); unique.add( Samantha Bee ); unique.add( Jon Stewart ); System.out.println(unique.size()); //prints 3 since //Jon Stewart is only added once We don't know the order that the HashSet stores it still, but we can do things like check if the value exists really quickly. 55

HashSet HashSet could be preferred over ArrayList if the following are true: -Duplicate elements are not allowed -You don't care about keeping track of the order you added elements in -Checking if a value is present or not is important and should be done quickly 56

Part 3: HashMap

Accessing Data in different ways We've seen with an array or an arraylist that you can access data by associating each data value with an index. The index doesn't necessarily have anything to do with the data itself. It merely represents where in the array or ArrayList the data is stored. Sometimes, the key or index itself is related to the data value. In addition, sometimes the key is not going to be an int. 58

Examples of fancier keys: -The most obvious example is a dictionary. The key is the word. The value is the definition of it. In this case both the key and value are Strings -Other examples: -StudentId ----> name (could be done with a regular array but would be a large waste of space) -name ----> StudentId 59

HashMap For this sort of scenario, you could create a HashMap A HashMap lets you relate a key to a value The key and value can be any types (not necessarily the same type) In a HashMap, things are stored in a smart way so that things can be accessed very fast. You can easily check if something is part of the HashMap or not. 60

HashMap HashMap<String, String> english = new HashMap<String,String>(); english.add( comp-202, hard ); english.add( dan p., tall ); System.out.println( The definition of comp-202 is + english.get( comp-202 )); 61