Compsci 201 Midterm 1 Review

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Big Java Chapter 16.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Data structures Abstract data types Java classes for Data structures and ADTs.
Sets, Maps and Hash Tables. RHS – SOC 2 Sets We have learned that different data struc- tures have different advantages – and drawbacks Choosing the proper.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Hash Tables and Hash Maps. DCS – SWC 2 Hash Tables A Set and a Map are both abstract data types – we need a concrete implemen- tation in order to use.
OOP Basics Classes & Methods (c) IDMS/SQL News
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Building Java Programs Generics, hashing reading: 18.1.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Slides by Donald W. Smith
CMSC 202 ArrayList Aug 9, 2007.
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
CS 215 Final Review Ismail abumuhfouz Fall 2014.
[ 4.00 ] [ Today’s Date ] [ Instructor Name ]
Chapter 19 Java Data Structures
Building Java Programs
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Software Development Java Collections
University of Central Florida COP 3330 Object Oriented Programming
A tree set Our SearchTree class is essentially a set.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Efficiency add remove find unsorted array O(1) O(n) sorted array
Searching.
Java Generics.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
CSE 143 Lecture 9 References and Linked Nodes reading: 3.3; 16.1
Building Java Programs
Building Java Programs
Building Java Programs
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
A tree set Our SearchTree class is essentially a set.
CMSC 202 ArrayList Aug 9, 2007.
slides created by Marty Stepp and Hélène Martin
Sets, Maps and Hash Tables
slides adapted from Marty Stepp and Hélène Martin
Can store many of the same kind of data together
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
CMSC 202 ArrayList Aug 9, 2007.
CS2110: Software Development Methods
Building Java Programs
slides created by Ethan Apter
Collections Framework
CSE 143 Lecture 25 Set ADT implementation; hashing read 11.2
CSE 143 Lecture 25 Advanced collection classes
Introduction to Data Structure
CSE 373 Separate chaining; hash codes; hash maps
Java Programming Language
Data Structures & Algorithms
slides created by Alyssa Harding
slides created by Marty Stepp
Review: libraries and packages
Hashing based on slides by Marty Stepp
slides created by Marty Stepp and Hélène Martin
Lecture 7: Linked List Basics reading: 16.2
CSE 143 Lecture 21 Advanced List Implementation
Java Basics – Arrays Should be a very familiar idea
Introduction to Java Collection
Presentation transcript:

Compsci 201 Midterm 1 Review Professor Peck Jimmy Wei 10/1/2013

List of Topics Data Structures References Big O Hashing Inheritance LinkedLists

Data Structures Arrays: fixed-length, typed Lists: variable-length, ordered Sets: variable-length, unordered, unique elements Maps: variable-length, unordered, key-value pairs

Data Structures In the following algorithms, what kind of data structure would you use and why? An algorithm that takes a number and returns its prime factors An algorithm that reads a file to create a data representation of a family tree An algorithm that checks a string for invalid characters and removes them from the string An algorithm that generates the first k numbers in some given number pattern (e.g. Fibonacci)

References Objects in Java are stored in memory, and are accessed through references—Java doesn’t trust us coders with direct memory access! The references themselves are stored in a different part of memory

ArrayList<String> References Process of creating a new Object: Declare typed reference ArrayList<String> list; Create new Object new ArrayList<String>(); Assign the reference to the Object myStringList = new ArrayList<String>(); Java Memory (Heap) ArrayList<String> list

ArrayList<String> References How do we create another reference to the same object? ArrayList<String> otherList = list; What happens if we manipulate list? Java Memory (Heap) ArrayList<String> list otherList list

References Consider the following code: What’s the output? public void firstMethod() { ArrayList<String> firstList = new ArrayList<String>(); firstList.add(“Jimmy”); ArrayList<String> secondList = firstList; System.out.println(secondList); secondList.add(“Andrew”); System.out.println(firstList); secondList = new ArrayList<String>(); secondList.remove(“Jimmy”); } [“Jimmy”] [“Jimmy”, “Andrew”] [] Output

References public static void secondMethod(Set<Integer> set) { Set<Integer> temp = new HashSet<Integer>(set); for (Integer item : set) { if (item % 2 == 0) { temp.remove(item); } public static void main(String[] args) { Set<Integer> nums = new HashSet<>(); nums.add(1); nums.add(2); …; nums.add(10); secondMethod(nums); System.out.println(nums); [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Output

Big O Used to measure scalability of performance Does not tell us how fast something runs in terms of absolute runtime—rather, tells us how performance of an algorithm scales as we increase input!!!

Big O Consider the following example: What is the input of the algorithm? How does performance scale as we increase the input? public void sum(int n) { int sum = 0; for (int i=0; i<n; i++) { sum += I; } return sum; O(n)

Big O Consider the following example: What is the input of the algorithm? How does performance scale as we increase the input? public void count(int k) { for (int i=0; i<k*k; i++) { for (int j=0; j<k; j+=2) { System.out.printf(“%d-%d\n”, j, i); } O(n^3)

Big O public long bigMethod(List<Integer> listOfNums) { long result = 0; for (int i=0; i<5; i++) { for (int k=0; k<listOfNums.size(); k*=2) { result += helper(listOfNums, k); } return result; public int helper(List<Integer> list, int firstK) { int sum = 0; for (int i=0; i<firstK; i++) { sum += list.get(i); return sum; Helper is O(n) BigMethod is O(nlogn)

Big O Big Oh of common data structures operations: Note that add for arrays, ArrayLists, and LinkedLists refers to adding to the end Access refers to grabbing a known element or index; search refers to checking for the existence of some element Data Structure Access Add Remove Search Array O(1) O(n) ArrayList LinkedList HashMap HashSet Data Structure Access Add Remove Search Array O(1) O(n) ArrayList LinkedList HashMap HashSet Data Structure Access Add Remove Search Array O(1) O(n) ArrayList LinkedList HashMap HashSet Data Structure Access Add Remove Search Array O(1) O(n) ArrayList LinkedList HashMap HashSet Data Structure Access Add Remove Search Array O(1) O(n) ArrayList LinkedList HashMap HashSet Data Structure Access Add Remove Search Array ArrayList LinkedList HashMap HashSet Helper is O(n) BigMethod is O(nlogn)

Hashing Java variables are either primitives or objects Primitives: int, long, float, double, short, etc… Objects: Strings, Arrays, Lists, Sets, Maps, etc... Primitives are stored as values Objects are stored as references

Hashing The difference between “.equals()” and “==“: Also note: “.equals()” tests for EQUALITY “==“ tests for IDENTITY Also note: Above statements are a simplification of using “.equals()” and “==“ for objects Primitives cannot invoke “.equals()”, but can be passed in as parameters

Hashing The hashCode() method returns an integer code for every object Rules: If a.equals(b), then a.hashCode() == b.hashCode() If !(a.equals(b)), then a.hashCode() == b.hashCode() || a.hashCode() != b.hashCode() Every object inherits .equals() and .hashCode(); if you overwrite one you MUST overwrite the other!

Hashing HashTables provide us with O(1) lookup/update Index Value “Jimmy” 1 2 42 3 4 5 6 “CS201” 7 8 9 List<String> Index Value 1 2 3 4 5 6 7 8 9 HashTables provide us with O(1) lookup/update Implemented as an array representing a fixed number of buckets Add keys to table based on calculated hashcode Add the following values (with given hashcodes) to the table: “Jimmy” (2510), 42 (42), List<String> (8509), “CS201” (5166)

Inheritance Java allows us to set up super/subclasses which inherit behavior from each other Consider the following classes: public class Sedan { public void start(); public void move(); public void honk(); } public class Bicycle { public void ringBell(); public class Train { public void board();

Inheritance We can set up a superclass for these: public class Vehicle{ public void start(); public void move(); } public class Sedan extends Vehicle { public void start(); public void move(); public void honk(); } public class Bicycle extends Vehicle { public void start(); public void move(); public void ringBell(); } public class Train extends Vehicle { public void start(); public void move(); public void board(); }

ArrayList<Integer>(); Inheritance How to use a superclass: Think back to the different parts of creating a new variable in Java… [Type] [VarName] = new [Instantiation] Only methods declared in [Type] are available! However, the actual methods that are executed are those in [Instantiation]!! List<Integer> myList = new ArrayList<Integer>();

Inheritance Let’s look at an example: If I write “Vehicle myVehicle = new Plane();”… public class Vehicle { public void start() { println(“Vehicle started”); } public void stop() { println(“Vehicle stopped”); public void move() { println(“Vehicle moved”); public class Plane extends Vehicle { public void takeoff() { println(“Plane takeoff”); } public void board() { println(“Plane boarding”); public void start() { board(); takeoff();

Inheritance Sometimes you want to declare a method without providing an implementation—such a method is called an abstract method An abstract method can only exist in an abstract class Abstract classes can be subclassed, but not instantiated An interface is an abstract class with only abstract methods

Inheritance public abstract class Vehicle { public void start() { println(“Vehicle started”); } public void stop() { println(“Vehicle stopped”); public abstract void move(); public interface PublicTransit { public abstract void board(); public abstract void unload(); } public class Plane extends Vehicle implements PublicTransit { public void move() { println(“Plane moving”); } public void board() { println(“Plane boarding”); } public void unload() { println(“Plane unloading”); } }

Inheritance For every abstract method in a superclass, a subclass must either declare it to be abstract (thus making the subclass also abstract) or implement it Note: no multiple inheritance in Java, i.e. can only extend ONE class However, one class can implement MULTIPLE interfaces

Inheritance public interface ClassA { public abstract void methodA(); } public class ClassD extends ClassB implements ClassA { public void methodA() { println(“ClassD MethodA!”); } public void methodB() { println(“ClassD MethodB!”); public void methodC() { println(“ClassD MethodC!”); public abstract class ClassB { public abstract void methodB(); } public class ClassC { public void methodC() { println(“ClassC MethodC!”); } 4 and 5 are valid Which are valid? 4) ClassD myClass = new ClassD(); 1) ClassA myClass = new ClassD(); myClass.methodB(); myClass.methodC(); 5) ClassB myClass = new ClassD(); 2) ClassB myClass = new ClassB(); 3) ClassC myClass = new ClassD();

Linked Lists How do we implement a LinkedList? Maintain a pointer to the HEAD of the list, and have every node point to the NEXT node private class Node { private int value; private Node next; private Node(int v, Node n) { value = v; next = n; }

Linked Lists Let’s do some practice with LinkedLists! Code is available for snarfing… First the basics: Adding to the list Removing from the list Then we’ll try trickier things… Removing every other element Moving elements to end of list Reversing the list ???

Linked Lists Adding an element to the list: public void add(int value) { if (head == null) { head = new Node(value, null); return; } Node current = head; while (current.next != null) { current = current.next; current.next = new Node(value, null);

Linked Lists Removing an element from the list: public void remove(int value) { if (head == null) { return; } Node first = null; Node second = head; while (second != null) { if (second.value == value) { if (first == null) { head = second.next; } else { first.next = second.next; } return; first = second; second = second.next;

Linked Lists Extra practice! We will implement the following LinkedList methods together: removeEveryOther(); moveToEnd(); reverse(); If we don’t finish all these problems, please feel free to practice them on your own!

Good luck! “An iteration over a thousand-length LinkedList begins with a single next call” -Timothy Shih-