CS 256 Final Exam Review
Declare an ArrayList of Strings
ArrayList<String> result = new ArrayList<String>
Protected Data Fields
Can be accessed by name only within its own class definition, any derived class, any class with the same package
Implement the comparable interface
public interface Comparable<T> { int compareTo(T other); }
Declare a main method with a throws clause for the FileNotFoundException
public static void main(String[] args) throws FileNotFoundException
In the derived class, which data members of the base class are visible (in other words, which data members can be accessed directly)?
those declared as public or protected
Syntax for try catch
try{ Code with possible errors } catch(possible error 1){ Do this } catch(possible error 2){ Do this }
AVL Tree Insertion, Removal, Search
- The data structure uses O(n) space - A single restructuring takes O(1) time • using a linked-structure binary tree - Searching takes O(log n) time • height of tree is O(log n), no restructures needed - Insertion takes O(log n) time • initial find is O(log n) • restructuring up the tree, maintaining heights is O(log n) - Removal takes O(log n) time • initial find is O(log n) • restructuring up the tree, maintaining heights is O(log n)
Exception
- an object - created when illegal operation is performed - can be checked or unchecked
Implementation of Interfaces
A class that implements an interface, must implement all methods of the interface
Deque Specifications
A double-ended queue Has operations that add, remove, or retrieve entries at both its front and back Combines and expands the operations of queue and stack
Tree Terminology 2
A node is reached from the root by a path • The length of the path is the number of edges that compose it • The subtree of a node is a tree rooted at a child of that node • The depth of a node is the length of the path from the root to that node
What is included in a linked list node?
A reference to its neighboring nodes A data element
Interface
A special type of declaration that lists a set of methods and their signatures
Interface v. Abstract Classes
Abstract classes can contain implemented methods Abstract classes can contain fields that are not static and final Abstract classes may have static fields and static methods
What is the subclass permitted to do?
Add new instance variables and methods Change the implementation of inherited methods
What do subclasses inherit from superclasses?
All public methods that it does not override All instance variables
What is an AVL Tree?
An AVL Tree is a binary search tree such that for every internal node v of T, the heights of the children of v can differ by at most 1
What is an ArrayList
An ArrayList stores a sequence of values whose number can change.
Big Oh
An algorithm's time requirement f(n) is of order at most g(n) f(n) = O(g(n))
Unchecked Exception
An exception that may or may not crop up during the natural execution of the application, and may not introduce a natural way for the application to recover.
Checked Exception
An exception that the programmer must catch and deal with
Insertion Sort
An insertion sort inserts the next unsorted element into its proper location within the sorted portion of an array
Other (Runtime)
Base class may provide implementation that may be either overriden by the derived classes or accepted unchanged by the derived classes.
abstract (Runtime)
Base class provides no implementation and is abstract. Derived class must provide implementation
Efficiency of a sequential (linear) search
Best case O(1) Locate desired item first Worst case O(n) Must look at all the items Average case O(n) Must look at half the items O(n/2) is still O(n)
What can a generic class be parameterized for?
Class Type
What happens if a line of code in a different class attempts to access a private member directly rather than through its accessor methods?
Compile Time Error
Identify characteristics of an Array
Composite, Structured Homogeneous Access by position
List Algorithm Efficiency, from smallest growth to largest growth
Constant - O(1) Logarithmic - O(log n) Linear - O(n) N-log-N - O(n log n) Quadratic - O(n^2) Cubic - O(n^3) Exponential - O(2^n)
Binary search tree: all nodes fulfill the property that:
Descendants to the left have smaller data values than the node data value - Descendants to the right have larger data values than the node data value
What does it mean to handle an exception?
Detect that than exception has occurred (or thrown) Deal with the problem by executing a block of code (catch the exception)
The nodes of a(n) ____ linked list class store two links: one to the next element and one to the previous one.
Doubly linked list
Which term describes the practice of protecting data within a class?
Encapsulation
A class that extends another class may implement only one interface.
False.
IOexception contains the subclasses:
FileNotFound MalformedURL UnknownHost
Choosing to use a linked list over an array may be a good idea when
Frequent random access of elements is not required
Runtime Exception contains the subclasses
IndexOutofBounds NullPointerException IllegalArgumentException
Expressions
Infix expressions Binary operators appear between operands a + b Prefix expressions Binary operators appear before operands + a b Postfix expressions Binary operators appear after operands a b + Easier to process - no need for parentheses nor precedence
Inorder Tree Traversal
Inorder (Left, Root, Right)
Selection Sort
Look at element, select the smallest one Swap with first element Look at remaining elements, select the next smallest Swap with second element Repeat ...until done
Interface v. Class
Interfaces are different in that : All methods are automatically public Cannot have instance variables Methods are usually abstract
final (Potentially Inlined)
Invariant over the inheritance hierarchy (method is never redefined)
Selection Sort Efficiency
Iterative method for loop executes n-1 times O(n2) Recursive selection sort performs same operations O(n2)
When should linked lists be used?
Linked lists should be used when you need to insert and remove elements efficiently from the front of the list.
static (Compile Time)
No controlling object
When is a method abstract?
No reasonable default implementation can be provided, and it must be defined in the inheritance hierarchy
Rather than storing values in an array, a linked list uses a sequence of ____.
Nodes
Binary Search Trees
Nodes contain Comparable options A node's data is greater than the data in the node's left subtree A node's data is less than the data in the node's right subtree
Tree Terminology
Nodes with children are the parent node of those children • children nodes are in the level below their parent node • Nodes with same parent are siblings • Node with no children is a leaf node • The only node with no parent is the root node - All others have one parent
Private Data Fields
Not accessible by name within definition of a method from another class (even derived classes) Still inherited by derived classes
Efficiency of binary search
O (log n)
Stack Specifications
Organizes entries according to order in which added Additions are made to one end, the top The item most recently added is always on the top (L.I.F.O.)
Postorder Tree Traversal
Postorder (Left, Right, Root)
Preorder Tree Traversal
Preorder (Root, Left, Right)
Declare an object of the PrintWriter class
PrintWriter out = new PrintWriter("output.txt"); If output.txt does not exist, it will create an empty file If output.txt exists, it will be emptied
Queue Specifications
Queue organizes entries according to order of entry Exhibits first-in, first-out behavior (FIFO) All additions are at the back of the queue Front of queue has items that were added first
What type of access does a LinkedList provide for its elements?
Sequential
Types of Algorithm Complexity
Space Complexity (how many resources need to be used) Time Complexity (how much time needs to be taken)
Level Order Traversal
Start with the lowest level (root) and go to each level, processing from left to right.
What is an Array?
Storage for a sequence of items of the same type
What is the meaning of the type parameter E, in the LinkedList<E> code fragment?
The elements of the linked list are any type supplied to the constructor.
What are method calls determined by?
The type of the actual object, not the type of the variable containing the object reference. (Dynamic Method Lookup)
Binary Search
This is used for searching in a sorted array. Test the middle element of the array. If it is too big. Repeat the process in the left half of the array, and the right half if it's too small. In this way, the amount of space that needs to be searched is halved every time, so the time is O(log n).
Circular Array Specifications
When queue reaches end of array - Add subsequent entries to the beginning Array behaves as though it were circular - First location follows last one
What happens when you throw an exception?
When you throw an exception, you are creating an object of an exception class and asking the calling method to handle the exception, and the normal control flow is terminated
To collect numbers in ArrayLists, you must use
Wrapper Classes
Linear Search
a sequential search, starts at the beginning of a list and checks every element of the list
Use the ___ and ___ methods to add and remove array list elements.
add, remove
The Comparable interface is implemented by some class and alpha and beta are objects of that class. Under what circumstance will alpha.compareTo(beta) return a negative integer?
alpha comes before beta.
Use the expression _____ to find the number of elements in an array.
array.length
A bounds error, which occurs if you supply an invalid array index can
cause your program to terminate.
finally block
code that must run regardless of the exception, will always run, regardless of breaks, even if exception is not caught
Checked exceptions
code will not compile without exception handling
Comparable Interface
compareTo() used to compare two objects a.compareTo(b); Called on object a, return values include: Negative: a comes before b Positive: a comes after b 0: a is the same as b
Generic Programming
creation of programming constructs that can be used with many different types
Runtime exceptions
don't need to be explicitly handled because they mainly occur as a result of a problem with the code logic.
Enhanced for loop to find maximum
double largest = values[0]; for(double element : values) { if(element > largest){ largest = element; } }
Declare an Array
double[] values;
Which clause is used to derive a new class from some other type?
extends implements
Which of the following are not allowed in an interface?
final methods
Code in the _________ block is always executed once the try block has been entered
finally
When an exception is detected, execution 'jumps' immediately to the
first matching catch block
Output every element in an array using an enhanced for loop
for (int myValue : myArray) { System.out.println(myValue); }
Use the ___ and ___ methods to access an array list element at a given index
get, set
Syntax for throwing an exception
if (amount > balance){ throw new IllegalArgumentException("Amount exceeds balance"); }
Priority Queue
insert(k, v) inserts an entry with key k and value v removeMin() removes and returns the entry with smallest key, or null if the the priority queue is empty min() returns, but does not remove, an entry with smallest key, or null if the the priority queue is empty size(), isEmpty()
In a linked list data structure, when does the reference to the first node need to be updated?
inserting into an empty list deleting from a list with one node
Stacks
int size(); boolean isEmpty(); E top(); void push(E element); E pop();
Syntax for filling an Array
int[] values = new int[11]; for(int = 0; i < values.length; i++){ values[i] = i*i; }
Intitialize a 2-dimensional Array using an initializer list
int[][] counts = { {1,0,1}, {1,0,1}, {1,0,1}, {1,0,1}, {1,0,1} }
Declare a 2-dimensional Array of ints
int[][] counts = new int[][];
Which of the following is true about an abstract base class?
no objects of the class can be created
For which methods is dynamic binding used?
non-static, non-final class methods
Which term describes the ability of a reference type to reference objects of several different types?
polymorphism
The term ____ is used in computer science to describe an access pattern in which the elements are accessed in arbitrary order.
random access
Use the ____ method to obtain the current size of an array list.
size
To signal an exceptional condition
use the throw statement to throw an exception object.
Initialize an Array
values = new double[10]