interface
sComparable<T>
interface:
public interface Comparable<T> {
int compareTo (T t);
}
Animal
to implement Comparable<Animal>
:
public abstract class Animal implements Comparable<Animal> {
...
public int compareTo (Animal a) {
if (this.getSpecies().equals(a.getSpecies())) {
return this.name.compareTo(a.name);
}
return this.getSpecies().compareTo(a.getSpecies());
}
}
Animal
s can now be sorted!An interface
is a contract:
interface
, you must provide certain functionalitySorting example:
Comparable
class
determines what is meant by comparisonSeparate interface from implementation
We’ve seen some data structures:
Data structures specify:
Used linked list data structure to implement
GenericList
add
and remove
SortedList
insert
and remove
Abstract data type specifies interaction (i.e., interface), not implementation
Two fundamental abstract data types
We’ll consider
Learning a new subject:
Eventually, my desk is covered with books!
Store books in a stack on my desk:
Successively removing books allows backtracking
Introducing the stack!
Push Sequential…Algorithms onto stack
Push Art of Multiprocessor Programming onto stack
Push Java Concurrency in Practice onto stack
Peek returns Java Concurrency in Practice
Pop returns & removes Java Concurrency in Practice
Pop returns & removes Art of Multiprocessor Programming
Stacks are useful in computing!
public interface SimpleStack<T> {
// push a new item on the top of the stack
public void push(T item);
// return the item currently at the top of the stack
public T peek();
// remove and return the item currently at the top of the stack
public T pop();
// check if the stack is empty
public boolean isEmpty();
}
How might we implement a stack?
How to store items?
How to push?
How to pop?
How to code it?
public class StackList<T> implements SimpleStack<T>, Iterable<T> {
// fields?
...
public void push(T item) {
...
}
public T peek() {
...
}
public T pop() {
...
}
class Node {
T item;
Node next;
public Node (T item) {
this.item = item;
next = null;
}
}
}