CS 300 EXAM TWO

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

define "stack ADT" what can you use to implement it? what are the three main operations on a stack?

abstract data type where items can only be added/removed from the TOP of the stack. "last-in first-out" ADT array, linked list can be used to implement push - push all other elements down to create a new TOP pop - pop off the TOP element, returns that element peek - returns the TOP element without removing

two variables, a and b, point to the same array. what statements will change what is stored in both, and what statements will change just one?

assignments to the contents of the array itself (a[1] = 2) will change the array that both point to. assignments to the variables themselves (a = something, b = something) only affect those variables themselves. its an issue of changing the object(the array) vs changing the reference(the variables a + b)

toString() - implicit calls, how it differs between objects

print statements that include nonstring objects can invoke an implicit call to toString() (ints, chars, etc). objects have their own versions of toString() which overrides the original

what does list.remove() do

removes and returns the element at the index from the parameter

int a = 5; String y = "yuh"; System.out.println("yuh" + a); System.out.println(y + a); System.out.println(y + 5); System.out.println(a + y); System.out.println(5 + y);

yuh5 yuh5 yuh5 5yuh 5yuh

traversal

"Walking through" a chain of nodes to reach a particular node is called...

ArrayList<Integer> itemsList = new ArrayList<Integer>(8); After itemsList.set(0, 99), what is the ArrayList's size?

0 or Error. the 8 parameter only sets initial capacity, not size, all arraylists are initialized w size 0 (empty) the 0th index doesn't exist yet, so attempting to access it would produce an error

what method types can be called on a list/collection of type <OBJECT> and how does this differ if the list type is more narrow?

<object> arraylists can only have methods from the object superclass called on them, otherwise there will be a compile time error. .intValue or some other specified method wouldn't be valid, but if the type is <integer> or <string>, that class' methods would be inherited by the arraylist and would become accessable

big O notation for a for loop with a constant number of iterations/operations within

A for loop of the form for (i = 0; i < N; ++i) {} that does not have nested loops or function calls, and does not modify i in the loop will always has a complexity of O(N).

for-each loop (what can and can't use it)

A looping construct primarily used for iterating when you want to simply view or display items in an array or ArrayList. NOT TO EDIT can't be used by iterators, can be used by iterable objects int totalNum = 0; for (int currentInt : listName){ totalNum += currentInt; }

when will .size() on an arraylist return 0? produce an error?

ArrayList<Integer> itemsList; --- arraylist has not been created, error ArrayList<Integer> itemsList = new ArrayList<Integer>(); --- arraylist is initialized to be empty, returns 0 (parenthesis can be empty or contain any number, a parameter here would indicate initial capacity and not size)

initialize an arraylist that can contain any object. initialize an arraylist that can contain only strings.

ArrayList<Object> obj = new ArrayList<Object>(); ArrayList<String> str = new ArrayList<String>();

common errors in recursion

BASE CASES: make sure all your bases are covered ;) also that your base cases can be reached, otherwise you could hit infinite recursion

Assuming itemList is 99 33 55 77 44, then itemList.remove(55) results in: 99 33 77 44

FALSE the parameter of add() and remove() refers to the index of an object, not its data

If a sorted list has elements 0 to 50 and the item being searched for is at element 6, how many times will a recursive method for a binary search be called?

First call: findMatch(0, 50), which checks element (0 + 50) / 2 = 25. Second call: findMatch(0, 25), which checks element 12 (0 + 25) / 2 = 12 (the fraction is truncated). Third call: findMatch(0, 12), which checks element 6 and finds the element.

rules for big O notation Big O notation equivalent to O(12·N +6·N^3 + 1000)? log2(N)? 3·N · O(N^2)? 2·N^3 + O(N^2)?

If f(x) is a sum of several terms, the highest order term (the one with the fastest growth rate) is kept and others are discarded. remove all constants. O(n^3) O(n^3) O(n^3)

Binary Search - define, what kind of list is necessary, what is the max search time for an N element list

Looking for an item in an already sorted list by eliminating large portions of the data on each comparison maximum number of steps required to reduce the search space to an empty sublist is .log2(N) + 1, reducing the search space by half on each search

What is the worst-case time complexity for the remove() operation for a linked-list

O(N) - worst case the element is at the end or not there so you make N comparisons

Which operation should usually be preceded by a check that the stack is not empty?

POP or PEEK, implementation for these operations may vary, but if there is no top item to check the behavior may be undefined and result in an error

T or F: After itemList.clear(), itemList.get(0) is an invalid access

TRUE

call stack

The call stack is all of the call frames of the currently executing function calls it expands with every method call, and diminishes as methods are fully executed also referred to as AR (activation records)

Object class

The name of the Java class that is the "mother" of all objects. All other Java class automatically inherit the Object class as the top-level parent class in the hierarchy. This class provides basic methods such as the toString, hashCode, and equals methods. (ALL USER DEFINED CLASSES ARE DERIVED FROM THE OBJECT CLASS)

ListIterator Methods

a list iterator is always hanging between two elements. next() accesses that next item, and moves the iterator to the next spot, previous() does the opposite set() accesses the last item that was accessed by the iterator and replaces it with the parameter passed in (item last returned either by a next() or previous()) add() adds the item between the prev and next items remove() removes the item that was last moved over, ie by next() or previous(). can only be used once after a next() or previous(), it'll fail if used twice in a row, fails after an add()

LinkedList methods, ListIterator class and its purpose, utilization

add, remove, get and set, size .listIterator() method returns a ListIterator object over the given LinkedList, of the list type. when defining a list iterator (generic class), its type (string etc) must be declared. list iterators are useful in that they store a current node reference, increasing the efficiency of traversing a linked list which would otherwise be pretty inefficient using get or set within a loop. use myIterator.hasNext() in a while loop to view every item in a list

purpose of generic methods and classes

avoiding redundant code

when arraylist is used vs linkedlist

both LinkedList and ArrayList implement a List LinkedList typically provides faster element insertion and removal at the list's ends (and middle if using ListIterator) ArrayList offers faster positional access with indices

list vs. array (similarities, differences)

both have data ordered so that each item has a specific spot in the lineage, both allow access/ability to add an item to a specific index, both allow access to size field, both require you to declare the type of data to be stored (string, car, integer, etc) differences: array - fixed size, list - fluid size array - can add an element at any spot within its max size, list - an empty list is ALWAYS size zero, and you can only add a new element in the 0 index. no adding elements at spot greater than current size array - can hold any type of data, list - can only hold OBJECTS, no prims

"derived from" "inherit"

child class is derived from the parent class child class inherits the parent class

how does the compiler react to a generic method being called with different objects as parameters? ex: Integer a = 10; Character b = 'b'; genMethod(a, b);

compile time error! gen methods must be called with all the same object type as parameters

runtime vs compile time polymorphism give an example of each

compile time- method overloading (compiler determines which method to call based on parameters) runtime- DERIVED CLASSES. (compiler can't make the determination, decided while the program is running) example of runtime poly: you make a list of type <generic item>. if you add a produce item to that list (child class), it automatically is implicitly cast as a generic item reference. if you then want to print the whole list, java's virtual machine does runtime poly to decide which print method to call based on the object type

collection, list, arraylist, linkedlist, relations

every collection type is an interface. list is a type of collection, and is an interface implemented by both linked list and array list. they have a lot of the same functionality/methods (get, set, size etc) but implementation is different. linked list is more optimal for insertion and removal, arraylist is faster for accessing individual elements based on their indeces

steps to solve a recursion eq

gen form of solution is a + b * c a = steps outside of recursion b = number of calls to recursive eq c = problem size passed to recursive call this is all equal to the actual form of the solution map it out, guess, replace on both sides with guessed solution (leave fuccked N term inside equation spot on the right as is)

how does the compiler react to a generic method being called?

it creates a separate method definition (unseen by the user/programmer) for each call specifically with that variable type as a parameter

purpose of recursion, costs of recursion

it will not make the code any faster, or reduce memory usage. USED FOR SIMPLICITY

QUEUE ADT definition

items inserted at the end of queue, removed from front of queue "first-in first-out" push - insert at end pop - remove and return from front think of it as a grocery line, the person who got in line first and has been waiting the longest will get to leave first

items = (E[])(new Object[INITSIZE]); what do this mean?

java doesn't allow you to create a new array of a generic type. so, what you gotta do is create a new object array and cast it to the generic type used by the method

what is a linear search?

just item by item dog. this is what you do when your shiit is unsorted

general code for a stack's push and pop operations using a linked list

null StackPush(stack, newItem) { ListPrepend(stack, newItem) // Insert as list head (top of stack) } StackPop(stack) { poppedItem = stack->head // Copy list head (top of stack) ListRemoveAfter(stack, 0) // Remove list head return poppedItem // Return popped item }

generic class type, declaring a variable of a generic class type

public class className <T extends Comparable<T>> { all variable types in the class are replaced with the generic type T a variable of the generic class type must specify the specific variable type ie: ClassName<Integer> x = new ClassName<Integer>(9999, 5555, 6666); ClassName<short> x = new ClassName<short>((short)9999, (short)5555, (short)6666);

create a method definition with a general type parameter bounded by the type bound Comparable. What does this mean? what type of variables can be passed in as parameters? what can be returned?

public static <TheType extends Comparable<TheType>> TheType tripleMin(TheType item1, TheType item2, TheType item3) { "TheType" can be replaced w literally anything. general structure : pub static <____ extends Comparable<____>> returnType methodName(_____ var1, ___ var2, ____ var3) { (where "___" contains the same thing) only objects that implement the comparable interface, meaning that they are able to be compared, like ints, chars, strings, references, etc the comparable<T> bound makes it so there are no compile time errors with a comparative statement being performed on a potentially non comparable variable the bound can also be a class type, and thus only methods from that class and its parent/derived classes can be used any object type that implements comparable can be returned, but make sure that you cast the parameters to the correct object type within the method to avoid any errors

what are the two main operations on a stack? how would you call each of these on a stack called "st" ?

push(9) would add a TOP element to the stack containing data - 9 pop() would remove and return the TOP element peek() would return but not remove the TOP element

Recursive Data Structure

referring to data in terms of itself. a string is a char followed by a string a list is a node followed by a list a sum is a number followed by a sum

Polymorphism

refers to determining which program behavior to execute depending on data types

remove first and last time complexity for array and linked list

remove first: array - O(N), must shift all elements to left linked list - O(1): list.setNext(list.getNext().getNext()); (list is where head node is stored) remove last: array - O(1): array.remove(numItems -1); remove last - O(N): traverse list to find item with null next pointer, assuming no tail pointer

default of toString()

returns class name and hashcode(a digestion of data stored in an instance variable)

iteration

set of instructions or structures are repeated in a sequence a specified number of times or until a condition is met. When the first set of instructions is executed again, it is called an iteration.

"Push 7", "Push 14", and "Push 9", "Pop" returns ____ for stack ADT for queue ADT Given numQueue: 5, 9, 1, Push(numQueue, 4) creates a list of order _____ for stack ADT for queue ADT

stack - 9 queue - 7 stack - 4, 5, 1, 9 for queue - 5, 1, 9, 4 (GET TO THE BACK OF THE LINE)

stack frame/stack overflow

stack frame - every method call allocates a new stack frame in memory. it stores local variables/params/method items. it is immediately deleted upon return stack overflow - a bunch of recursive method calls can overflow this stack frame and crash ya shit

what is the purpose of a recursive method? what is a "base case"

the purpose of a recursive method is to solve a large problem by several discrete iterations of the same type of solution a base case contains the actual methodology of the solution to the problem. when entering a method, if the params meet the base criteria, do that, else trigger another method call for the recursive case, picture the equation creating a tree. if you create a method for a fibonacci num, each recursive method call in that return statement has a branch of return statements that are in turn going to compose its value

is the size of the stack frame static? what can affect the speed at which a stack frame may be overflowed?

the size of the stack frame can be made larger or smaller based on how much memory the sum of its parameters may take up, ie less space for all ints and more space for several arraylists the stack frame can be overflowed more easily by declaring local variables that require a lot of memory (lotsa strings/large arraylists/arrays)

linked list implementation - what are the classes involved with creating a linked list

there is a listNode class - stores variables contained in each node, as well as setters and getters for those fields there is also a LinkedList class - has a field that stores the head node, rather than other list classes that will store the entire list - possible lastNode pointer as well bc reduction of time complexity - number of items

Given the following interface and classes definitions: public interface Animal{ } public class Pet { } public class Cat extends Pet implements Animal{ } public class Dog extends Pet implements Animal{ } public class WildAnimal implements Animal{ } public class PetParty<T extends Pet> { } True or False? T can be Cat.

true

can a generic method include two bound types? (ie comparable and something else lol)

yee! modifiers <T1 extends Bound1, T2 extends Bound2> ReturnType (ReturnType var1, ReturnType var2 .....


Set pelajaran terkait

Psychology Midterm Study Guide Chapter 4

View Set

practice questions for pharm test #5

View Set

ASTRO 7N Unit 1 Part 1: Gravity Lesson

View Set

MGMT 456 Ch. 14 Comp of Special Groups

View Set

Chapter 5 Questions for Review - Demand and Supply

View Set