CSCI1933 Lecture9
CSCI1933 Lecture9
• Midterm 2 in 2 weeks!
Midterm 2
• Thursday, April 7, 6:30-8:30pm
• Closed book, closed computer
• You are allowed 1 page (8.5” x 11”)
(2 sides) of handwritten notes
- “Exceptions” in Java
- Iterators
/**
A class that implements a list of objects by using an array.
Entries in a list have positions that begin with 1.
Duplicate entries are allowed. */
public AList()
{
this(DEFAULT_CAPACITY);
} // end default constructor
Implementing add method
Task: Adds newEntry to the end of the list.
Input: newEntry is an object.
Output: None.
if(numberOfEntries == list.length) {
// Error--list full!! Report or handle here
}
else {
list[numberOfEntries + 1] = newEntry;
numberOfEntries++;
}
} // end add
Implementing second add method
} // end add
mylist.remove(2)
Note: we
need the
opposite of
“makeRoom”
method
here
removeGap
Carrano and Henry, Data Structures and Abstractions with Java.
remove method implementation
public T remove(int givenPosition)
{
checkIntegrity();
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
{
Linked list:
• List is organized by keeping track of start (or end) only
• Each element of the list knows about the next element in the list
Linked list (LList) implementation
• Now that we understand the logic, let’s think about how we’d
implement a “linked list”
• Steps:
– what type of structure (e.g. array) should we use to store
data elements (objects) in the list?
– how do we implement the standard list methods
• NOTE: we need all of the same methods that we used
for the array-based list, we’re just changing how they
interact with the data stored in this list
public class LList < T > implements ListInterface < T > {
}
What type of structure/variable will we
need to store elements of a linked list?
• Requirements?
• should keep track of our data!
(e.g. patient info, illness, etc.)
• needs to store a reference to
the next patient
The Node inner class
public class LList < T > implements ListInterface < T > {
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node(T dataPortion)
{
data = dataPortion;
next = null;
} // end constructor
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor data next
} // end Node
public LList()
{
clear();
} // end default constructor
First, let’s start by thinking of the possible starting states for the
list...
Adding elements to a linked list
• Possible cases:
– adding element to an empty list
– adding element to a list with existing
elements
Adding to the End of the List
(empty case)
if (isEmpty()) {
} // end if
length++;
return true;
} // end add
Adding elements to a linked list
public boolean add(T newEntry)
{
Node newNode = new Node(newEntry);
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
Node lastNode = getNodeAt(length);
} // end if
length++;
return true;
} // end add
Adding to the End of the List (non-
empty case)
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
Node lastNode = getNodeAt(length);
} // end if
length++;
return true;
} // end add
New material
Overview of today’s material
- Lists
- Finish linked list implementation
- Comparison of array-based list
implementation to linked list implementation
- “Exceptions” in Java
- Iterators
?
}
}
Exercise: We used a helper function getNodeAt
– how do we implement this?
public class LList<T> implements ListInterface<T>
{
private Node firstNode; // reference to first node
private int length; // number of entries in list
currentNode=firstNode;
for(int counter=1; counter < givenPosition; counter++) {
currentNode = currentNode.next;
}
}
return currentNode;
}
}
Now, how about adding elements in
the middle of a linked list?
public boolean add(int newPosition, T newEntry)
Error conditions?
Case 1: adding at Beginning of the List
• add(T)
• add(i, T)
• clear(), getLength(), isEmpty()
• remove(i)
• replace(i,T)
• getEntry(i)
• contains(T)
Removing an element from a linked list
public T remove(int givenPosition)
(see Carrano and Henry, Chapter 12, for details on linked list implementation)
Overview of today’s material
- Lists
- Finish linked list implementation
- Comparison of array-based list
implementation to linked list implementation
- “Exceptions” in Java
- Iterators
• Which is better?
– Space complexity?
– Time complexity?
Comparison of array and linked list List
implementations
• Which is better?
– Space?
• Array List: wastes memory for each unfilled
slot in the array
• Linked List: only create one node per element,
BUT requires memory overhead of links
Comparison of array and linked list List
implementations
• Which is better?
Assume N elements– what’s the number of operations in the worst case?
– Time complexity?
• getEntry (int position)
• Array List: ?
• Linked List: ?
– Time complexity?
• getEntry (int position)
• Array List: O(1) (doesn’t depend on the size of the
array)
• Linked List: requires traversal of all preceding elements
(worst-case: last element, complexity ~ O(N))
Comparison of array and linked list List
implementations
• Which is better?
Assume N elements– what’s the number of operations in the worst case?
– Time complexity?
• remove(int position)
• Array List: ?
• Linked List: ?
– Speed?
• remove(int position)
• Array List: needs reshuffling (worst case: first
element, complexity ~ O(N))
• Linked List: simply “rewire” links in constant time,
but we still need to find this element (worst case:
last element, complexity ~O(N))
Summary of Pros and Cons of a linked list
implementation
• The linked list can grow as large as necessary
• Can add and remove nodes without shifting existing
entries
But …
• Must traverse a chain to determine where to make
addition/deletion
• Retrieving an entry requires traversal
– As opposed to direct access in an array
• Requires more memory for links
– But does not waste memory for oversized array
Variations on the linked list
• Also include a tail reference (reference to the
last node of the list) Why?
...
}
Adding elements to a linked list
public boolean add(T newEntry)
{
Node newNode = new Node(newEntry);
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
Node lastNode = getNodeAt(length);
} // end if
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
lastNode.next = newNode;
lastNode = newNode;
} // end if
length++;
return true;
} // end add
Java Class Library: The Class LinkedList
- Lists
- Finish linked list implementation
- Comparison of array-based list
implementation to linked list implementation
- “Exceptions” in Java
- Iterators
• Two actions:
– Create “throw” an exception
– Handle exceptions
Exception example
public class FileReader {
public FileReader() {
}
while (fileInput.hasNext()) {
result = result + fileInput.nextLine();
}
} catch(FileNotFoundException e) {
System.out.println("Sorry, can't find file!");
System.out.println(e.getMessage());
System.exit(1);
}
return result;
}
}
Main:
FileReader seqFile = new FileReader();
Our example:
try {
File f = new File(filename);
Scanner fileInput = new Scanner(f);
while (fileInput.hasNext()) {
result = result + fileInput.nextLine();
}
} catch(FileNotFoundException e) {
System.out.println("Sorry, can't find file!");
System.out.println(e.getMessage());
System.exit(1);
}
What happens if we don’t use try-catch?
public String readSequenceFromFile(String filename) {
//Getting input from a text file
String result = "";
File f = new File(filename);
Scanner fileInput = new Scanner(f);
while (fileInput.hasNext()) {
result = result + fileInput.nextLine();
}
return result;
}
while (fileInput.hasNext()) {
result = result + fileInput.nextLine();
}
return result;
}
Another option: pass the exception upward
public String readSequenceFromFileVer2(String filename)
throws FileNotFoundException {
//Getting input from a text file
String result = "";
File f = new File(filename);
Scanner fileInput = new Scanner(f);
while (fileInput.hasNext()) {
result = result + fileInput.nextLine();
}
return result;
}
• Unchecked exceptions
• relates to error conditions that are triggered by badly written code (i.e. are the
programmer’s fault). Compiler doesn’t enforce handling of these
- “Exceptions” in Java
- Iterators
5 9 23 34
5 9 23 34
5 9 23 34
5 9 23 34
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Iterator.html
How would we use an iterator?
//for an already defined List called “list”
Iterator<String> it = list.iterator();
while( it.hasNext() ) {
String temp = it.next();
System.out.println( temp );
}
public ArrayListWithIterator()
{
this(DEFAULT_CAPACITY);
} // end default constructor
….
Provide method to
public Iterator<T> iterator()
create iterator
{
return new IteratorForArrayList();
} // end iterator
….
private IteratorForArrayList()
{
nextIndex = 1; // Iteration begins at list's first entry
wasNextCalled = false;
} // end default constructor
} // end IteratorForArrayList
} // end ArrayListWithIterator
private IteratorForArrayList()
{
nextIndex = 1; // Iteration begins at list's first entry
wasNextCalled = false;
} // end default constructor
} // end IteratorForArrayList
} // end ArrayListWithIterator
Method hasNext
Carrano and Henry, Data Structures and Abstractions with Java.
Array-Based Implementation
Method hasNext
Carrano and Henry, Data Structures and Abstractions with Java.
Array-Based Implementation
public T next()
{
checkIntegrity();
if (hasNext())
{
wasNextCalled = true;
T nextEntry = list[nextIndex];
nextIndex++; // Advance iterator
return nextEntry;
}
else
throw new NoSuchElementException("Illegal call to next(); " +
"iterator is after end of list.");
} // end next
Method next
The array of list entries and nextIndex (a) just before the call to
next; (b) just after the call to next but before the call to remove;
(c) after the call to remove
Carrano and Henry, Data Structures and Abstractions with Java.
Array-Based Implementation
public void remove()
{
checkIntegrity();
if (wasNextCalled)
{
// nextIndex was incremented by the call to next, so it is
// 1 larger than the position number of the entry to be removed
ArrayListWithIterator.this.remove(nextIndex − 1);
nextIndex−−; // Index of next entry in iteration
wasNextCalled = false; // Reset flag
}
else
throw new IllegalStateException("Illegal call to remove(); " +
"next() was not called.");
} // end remove
ArrayList<Integer> list;
//code to create and fill list here
int total = 0;
for( int x : list )
total += x;
Java Collection interface
(extends the Iterable
interface)
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html
Iterator summary
• Iterators provide a convenient interface for
traversing through elements of a given data
structure
• Inner class implementations can usually be made
more efficient
• Many built-in Java data structures provide
iterators (all classes that implement Collection
interface)
- “Exceptions” in Java
- Iterators
Later:
• Dictionaries (hashes)
• Graphs
• Trees
A Stack abstract data type
• 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
• Items can only be removed from the top
The program stack at 3 points in time; (a) when main begins execution; (b)
when methodA begins execution, (c) when methodB begins execution.
In Main:
int result;
result = factorial(4);
for(char c:chars) {
st.push(c);
}
After complete traversal, if there are any starting brackets left in the stack– not
balanced
Check our solution on our example
Create an empty stack
After complete traversal, if there are any starting brackets left in the stack– not balanced