LinkedList test extends StackTest - java

I need help to understand how the testing should go through. I should implement the test method in stacktest.java ( have already done that). Then extend Stacktest with LinkedlistTest ( i have already done that). Then add super.setUp() as the first line in LinkedListTest.setUp (I have done that). But the one overriden method is getIntegerStack that I implement in the LinkedListTest, but then i Get a error " 'getIntegerStack()' in 'LinkedListTest' clashes with 'getIntegerStack()' in 'StackTest'; attempting to use incompatible return type " I dont know how to fix it. I have tested but i dont want to import java.util.stack in StackTest.java, because then my top() method does not work. What should I do?
The testing:
StackTest.java is an abstract test class.
For each implementation of Stack, one may simply extend StackTest with an implementing test class. The only method that should be overridden is StackTest.getIntegerStack, which should simply return an instance of a class that implements Stack. See the setUp method in StackTest and try to understand how this works.
In your case, you should extend StackTest with a test class called LinkedListTest.
you must add a call to super.setUp(); as the first line in LinkedListTest.setUp.
TODO: How should i make the getIntegerStack() do work.
stack interface class:
public interface Stack <T> {
void push ( T elem);
T pop();
T top();
int size();
boolean isEmpty();
}
LinkedList class.
import java.util.EmptyStackException;
import java.util.NoSuchElementException;
/**
* A singly linked list.
*/
public class LinkedList<T> implements Stack <T> {
private ListElement<T> first; // First element in list.
private ListElement<T> last; // Last element in list.
private int size; // Number of elements in list.
/**
* A list element.
*/
private static class ListElement<T> {
public T data;
public ListElement<T> next;
public ListElement(T data) {
this.data = data;
this.next = null;
}
}
/**
* Creates an empty list.
*/
public LinkedList() {
this.first = null;
this.last = null;
this.size = 0;
}
/**
* Inserts the given element at the beginning of this list.
*
* #param element An element to insert into the list.
*/
public void addFirst(T element) {
ListElement<T> firstElement = new ListElement<>(element);
if (this.size == 0){
this.first = firstElement;
this.last = firstElement;
}
else{
firstElement.next = this.first;
this.first = firstElement;
}
this.size ++;
}
/**
* Inserts the given element at the end of this list.
*
* #param element An element to insert into the list.
*/
public void addLast(T element) {
ListElement<T> lastElement = new ListElement<>(element);
if(this.size ==0){
this.first = lastElement;
}
else{
this.last.next = lastElement;
}
this.last = lastElement;
this.size ++;
}
/**
* #return The head of the list.
* #throws NoSuchElementException if the list is empty.
*/
public T getFirst() {
if (this.first != null){
return this.first.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* #return The tail of the list.
* #throws NoSuchElementException if the list is empty.
*/
public T getLast() {
if(this.last != null){
return this.last.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* Returns an element from a specified index.
*
* #param index A list index.
* #return The element at the specified index.
* #throws IndexOutOfBoundsException if the index is out of bounds.
*/
public T get(int index) {
if(index < 0|| index >= this.size){
throw new IndexOutOfBoundsException();
}
else{
ListElement<T>element = this.first;
for(int i = 0; i < index; i++){
element = element.next;
}
return element.data;
}
}
/**
* Removes the first element from the list.
*
* #return The removed element.
* #throws NoSuchElementException if the list is empty.
*/
public T removeFirst() {
if(this.first != null || this.size != 0){
ListElement<T> list = this.first;
this.first = first.next;
size --;
if(size()==0){
last = null;
}
return list.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* Removes all of the elements from the list.
*/
public void clear() {
this.first = null;
this.last = null;
this.size =0;
}
/**
* Adds the element to the top of the stock.
* #param elem
*/
#Override
public void push(T elem) {
ListElement <T> list = new ListElement<>(elem);
if( first == null){
first = list;
last = first;
} else{
list.next = first;
first = list;
}
size ++;
}
/**
* Removes and returns the top element in stack,
* that is the element that was last added.
* Throws an EmptyStackException if stack is empty.
* #return the top element in the stack.
*/
#Override
public T pop(){
if(isEmpty()){
throw new EmptyStackException();
}else{
ListElement <T> list = first;
first = first.next;
size --;
return list.data;
}
}
/**
* returns the top element in the stack without removing it.
* Throws an EmptyStackException if stack is empty.
* #return the top element.
*/
#Override
public T top() {
if(isEmpty()){
throw new EmptyStackException();
}else{
return first.data;
}
}
/**
* Returns the number of elements in the stock
* #return The number of elements in the stock.
*/
public int size() {
return this.size;
}
/**
* Note that by definition, the list is empty if both first and last
* are null, regardless of what value the size field holds (it should
* be 0, otherwise something is wrong).
*
* #return <code>true</code> if this list contains no elements.
*/
public boolean isEmpty() {
return first == null && last == null;
}
/**
* Creates a string representation of this list. The string
* representation consists of a list of the elements enclosed in
* square brackets ("[]"). Adjacent elements are separated by the
* characters ", " (comma and space). Elements are converted to
* strings by the method toString() inherited from Object.
*
* Examples:
* "[1, 4, 2, 3, 44]"
* "[]"
*
* #return A string representing the list.
*/
public String toString() {
ListElement<T> listOfElements = this.first;
String returnString = "[";
while(listOfElements != null) {
returnString += listOfElements.data;
if(listOfElements.next != null){
returnString += ", ";
}
listOfElements = listOfElements.next;
}
returnString += "]";
return returnString;
}
}
Testclasses:
import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.lang.Integer;
import java.util.EmptyStackException;
import java.util.stream.IntStream;
/**
* Abstract test class for Stack implementations.
*
* Implementing test classes must only implement the getIntegerStack
* method. Be careful not to override ANY other methods!
*
*/
public abstract class StackTest{
#Rule public Timeout globalTimeout = Timeout.seconds(5);
private Stack<Integer> stack;
private int[] valuesInStack;
private int initialStackSize;
private Stack<Integer> emptyStack;
#Before
public void setUp() {
valuesInStack = new int[] {3, 4, 1, -123, 4, 1};
initialStackSize = valuesInStack.length;
stack = getIntegerStack();
pushArrayToStack(valuesInStack, stack);
emptyStack = getIntegerStack();
}
/**
* Push an array to the stack, in order.
*
* #param array An int array.
* #param stack A Stack.
*/
private void pushArrayToStack(int[] array, Stack<Integer> stack) {
for (int i = 0; i < array.length; i++) {
stack.push(array[i]);
}
}
/**
* This is the only method that implementing classes need to override.
*
* #return An instance of Stack.
*/
protected abstract Stack<Integer> getIntegerStack();
#Test
public void topIsLastPushedValue() {
// Arrange
int value = 1338;
// Act
emptyStack.push(value);
stack.push(value);
int emptyStackTop = emptyStack.top();
int stackTop = stack.top();
// Assert
assertThat(emptyStackTop, equalTo(value));
assertThat(stackTop, equalTo(value));
}
// HELPERS
/**
* Pops the desired amount of elements.
*
* #param stack A Stack.
* #param amountOfElements The amount of elements to pop.
*/
private void popElements(Stack<Integer> stack, int amountOfElements) {
for (int i = 0; i < amountOfElements; i++) {
stack.pop();
}
}
/**
* Class used for stream operations when both actual and expected values
* need to be gather in conjunction.
*/
private class ResultPair<T> {
public final T actual;
public final T expected;
public ResultPair(T actual, T expected) {
this.actual = actual;
this.expected = expected;
}
}
}
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Test class for LinkedList
*
* The following invariants are checked for several different states and for
* each of the methods that mutate the list.
*/
public class LinkedListTest extends StackTest{
/* A sequence of integers */
private int[] elements;
/* An empty linked list */
private LinkedList<Integer> list;
#Before
public void setUp() {
super.setUp();
list = new LinkedList<Integer>();
elements = new int[]{-919, 388, 67, -248, -309, -725, 904, 53,
90, -469, -559, 256, 612, 366, -412, -221,
347, -921, -978, 324, -858, 480, -443, 891,
329, -5, 878, -538, 445, -366, 760, 52};
}
/**
* This is the only method that implementing classes need to override.
*
* #return An instance of Stack.
*/
#Override
protected Stack<Integer> getIntegerStack() {
return null;
}
}

In StackTest your abstract method protected abstract Stack<Integer> getIntegerStack(); should return the Stack interface you created. At least that's what it looks like due to no imports of classes named Stack. But in LinkedListTest the method implementation returns java.util.Stack. Note this:
import java.util.Stack;
It's the last import in LinkedListTest.
The declared method is expecting implementors to return your.package.Stack, but you are returning java.util.Stack, and those need to match, no way around that. So remove the aforementioned import, there will be no more compilation errors, and you can start testing.
Edit:
If your Stack interface does not reside in any additional packages, you should just remove the import. If you have declared it in some package of your own, you should change the import to
import your.package.Stack;
where your.package. is whatever package you declared the interface in.
About the implementation of the abstract method, you should return a new instance of Stack, as written in the comments. That means returning new instance of your LinkedList implementation.

Related

cs 61b project1b Cannot resolve method get in Deque

I wrote these codes in Idea. The IDE throws "can't resolve method get in Deque.java" when I finished Palindrome.java. How come? I actually did that in the Deque.java. Although in the LinkedListDeque inherited the get() method from the origin LinkList.
I found another solution by changing
Deque stringDeque = wordToDeque(word);
to
LinkListDeque stringDeque = (LinkListDeque) wordToDeque(word);
But I am still curious about how cannot find get in Deque.
class diagram here
Deque interface
/** Create an interface in a new file named Deque.
* java that contains all of the methods that appear in both ArrayDeque and LinkedListDeque.
* #param <Item>
*/
public interface Deque<Item> {
int size = 0;
/** Adds an item of type T to the front of the deque. */
void addFirst(Item item);
/** Adds an item of type T to the back of the deque. */
void addLast(Item item);
/** Returns true if deque is empty, false otherwise. */
default boolean isEmpty() {
return size == 0;
};
/** Prints the items in the deque from first to last,
* separated by a space. Once all the items have been printed, print out a new line. */
void printDeque();
/** Removes and returns the item at the front of the deque. If no such item exists, returns null. */
Item removeFirst();
/** Removes and returns the item at the back of the deque. If no such item exists, returns null. */
Item removeLast();
/** Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth.
* If no such item exists, returns null. Must not alter the deque! */
Item get(int index);
}
class LinkedLinkDeque.java
import java.util.LinkedList;
import java.util.NoSuchElementException;
/**
* Isn't this solution kinda... cheating? Yes.
*/
public class LinkedListDeque<Item> extends LinkedList<Item> implements Deque<Item> {
#Override
public void printDeque() {
System.out.println("dummy");
}
public Item getRecursive(int i) {
return get(i);
}
#Override
public Item removeFirst() {
try {
return super.removeFirst();
} catch (NoSuchElementException e) {
return null;
}
}
#Override
public Item removeLast() {
try {
return super.removeLast();
} catch (NoSuchElementException e) {
return null;
}
}
}
Palindrome.java
import java.util.Deque;
import java.util.LinkedList;
public class Palindrome {
/** Given a String, wordToDeque should return a Deque
* where the characters appear in the same order as in the String.
* #param word
*/
public Deque<Character> wordToDeque(String word) {
Deque<Character> stringDeque = new LinkedListDeque<>();
for (String s : word.split("")) {
stringDeque.addLast(s.charAt(0));
}
return stringDeque;
}
/** Return true if the given word is a palindrome, and false otherwise. */
public boolean isPalindrome(String word) {
if (word.length() == 0 || word.length() == 1) {
return true;
}
Deque stringDeque = wordToDeque(word);
int index = word.length() / 2;
for (int i = 0; i < index; i += 1) {
if (stringDeque.get(i) != stringDeque.get(word.length() - i - 1)) { return false; }
}
return true;
}
}
You have your own Deque interface but you are also working with the java.util.Deque interface. This can result in problems as the interface Deque is defined twice in different namespaces. Specially in your Palindrome.java file you are using the java.util.Deque interface because of the import java.util.Deque line at the top and NOT your Deque interface as you might expect.
Because of that you get the error message that the get(int) method is missing. That is correct, the java.util.Deque method does not define a get(int) method (but the java.util.List interface does).
Do not name classes with names which already exists in java. As you see that can result in naming conflict/issues.

Cannot pass ArrayList<Integer> to method with arg type ArrayList<T>

I'm trying to write a method to construct a binary search tree from a given ArrayList that could contain any type of comparable object T, using:
#SuppressWarnings("unchecked")
public boolean buildFromList(ArrayList<T> list) {
if (this != null) {
root = null;
}
for (T toInsert : list) {
if (this.find(toInsert) == true) {
return false;
}
this.insert(toInsert);
}
return true;
}
but when I try to pass it an ArrayList, I get an error stating that "cannot make a static reference to a non-static type T," even though it should accept any object that implements Comparable, which should be Integer, so what am I missing? The code that I'm using to create the ArrayList to pass it is:
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(3);
a.add(2);
a.add(4);
a.add(-1);
System.out.println(buildFromList(a));
The full code is:
import java.util.ArrayList;
/**
* Binary Search Tree Class
*
* The head class for a binary search tree implementation.
*
* #author YOURID
* #param <Comparable> Type of data to store in the binary tree
*/
public class BinarySearchTree<T extends Comparable<T>> {
/**
* A reference pointer to the root of the tree
*/
private BinaryTreeNode<T> root;
private StringBuilder sb = new StringBuilder("");
/**
* Default constructor
*
* Creates a binary tree object with null root note (empty tree)
*/
public BinarySearchTree() {
this(null);
}
/**
* Constructor
*
* Creates a binary tree object with the given node as root
*
* #param newRoot The root of the tree
*/
public BinarySearchTree(BinaryTreeNode<T> newRoot) {
this.root = newRoot;
}
/**
* Get the root of the tree
*
* #return The root of the tree
*/
public BinaryTreeNode<T> getRoot() {
return root;
}
/**
* Set the root of the tree
*
* #param root The new root of this tree
*/
public void setRoot(BinaryTreeNode<T> root) {
this.root = root;
}
/**
* Returns the size of the tree (that is, the
* number of nodes in the tree).
*
*/
public int size() {
if (this.root != null) {
return root.size();
}
return 0;
}
/**
* Returns the height of the tree.
*
*/
public int height() {
if (root != null) {
return root.height();
}
return 0;
}
/**
* Find if an element exists
*
* Checks to see if the value val appears in the
* tree (recursively). Returns true if it appears
* and false otherwise.
*
* #param val The value to find
* #return True if the tree contains the value, false otherwise
*/
public boolean find(T val) {
return findHelper(root, val);
}
private boolean findHelper(BinaryTreeNode<T> current, T value) {
if (current == null) {
return false;
}
if (value.compareTo(current.getData()) == 0) {
return true;
}
return value.compareTo(current.getData()) < 0
? findHelper(current.getLeft(), value)
: findHelper(current.getRight(), value);
}
/**
* Insert an element
*
* Inserts val into the tree where it should appear, returning
* true on success and false otherwise
*
* #param val The value to insert
* #return True on success, false otherwise
*/
#SuppressWarnings("unchecked")
public boolean insert(T val) {
root = insertNode(root, new BinaryTreeNode<T>(val));
return this.find(val);
}
// private recursive call
#SuppressWarnings({ "rawtypes", "unchecked" })
private BinaryTreeNode insertNode(BinaryTreeNode currentParent, BinaryTreeNode newNode) {
if (currentParent == null) {
return newNode;
} else if (newNode.getData().compareTo(currentParent.getData()) > 0) {
currentParent.setRight(insertNode(currentParent.getRight(), newNode));
} else if (newNode.getData().compareTo(currentParent.getData()) < 0) {
currentParent.setLeft(insertNode(currentParent.getLeft(), newNode));
}
return currentParent;
}
/**
* Return a string that represents the data held at each
* node following the rules of an in-order traversal.
*
* Covered in class Wednesday, April 22
*/
public String inOrder() {
sb.setLength(0);
return outputInOrder(root);
}
public String outputInOrder(BinaryTreeNode<T> node) {
if (node != null) {
if (node.getLeft() != null) {
outputInOrder(node.getLeft());
}
sb.append("(" + node.getData() + ")");
if (node.getRight() != null) {
outputInOrder(node.getRight());
}
return sb.toString();
}
return "";
}
/**
* Return a string that represents the data held at each
* node following the rules of a post-order traversal.
*
* Covered in class Wednesday, April 22
*/
public String postOrder() {
sb.setLength(0);
return outputPostOrder(root);
}
public String outputPostOrder(BinaryTreeNode<T> node) {
if (node != null) {
outputPostOrder(node.getLeft());
outputPostOrder(node.getRight());
sb.append("(" + node.getData() + ")");
return sb.toString();
}
return "";
}
/**
* Build from a list
*
* Build the tree from the given list, overwriting any tree data
* previously stored in this tree. Should read from beginning to
* end of the list and repeatedly call insert() to build the tree
*
* If the tree is not empty when this method is called, you should
* empty the tree before adding any elements in list.
*
* #param list The list from which to build the tree
* #return True if successfully built, false otherwise
*/
public boolean buildFromList(ArrayList<T> list) {
if (this != null) {
root = null;
/**root.setLeft(null);
root.setRight(null);*/
}
for (T toInsert : list) {
if (this.find(toInsert) == true) {
return false;
}
this.insert(toInsert);
}
return true;
}
#SuppressWarnings("unchecked")
public boolean buildFromList(ArrayList<T> list) {
if (this != null) {
root = null;
}
for (T toInsert : list) {
if (this.find(toInsert) == true) {
return false;
}
this.insert(toInsert);
}
return true;
}
/**
* toString method
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return inOrder();
}
/**
* Main method
*
* For testing, etc
*
* #param args Command line arguments
*/
public static void main(String[] args) {
BinarySearchTree<Integer> tree = new BinarySearchTree<Integer>();
BinaryTreeNode<Integer> n1 = new BinaryTreeNode<Integer>();
n1.setData(0);
BinaryTreeNode<Integer> n2 = new BinaryTreeNode<Integer>();
n2.setData(1);
BinaryTreeNode<Integer> n3 = new BinaryTreeNode<Integer>();
n3.setData(-1);
BinaryTreeNode<Integer> n4 = new BinaryTreeNode<Integer>();
n4.setData(2);
BinaryTreeNode<Integer> n5 = new BinaryTreeNode<Integer>();
n5.setData(-2);
BinaryTreeNode<Integer> n6 = new BinaryTreeNode<Integer>();
n6.setData(4);
BinaryTreeNode<Integer> n7 = new BinaryTreeNode<Integer>();
n7.setData(-6);
tree.insert(n1.getData());
tree.insert(n2.getData());
tree.insert(n3.getData());
tree.insert(n4.getData());
tree.insert(n5.getData());
tree.insert(n6.getData());
tree.insert(n7.getData());
System.out.println(tree.toString());
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(3);
a.add(2);
a.add(4);
a.add(-1);
System.out.println(buildFromList(a));
}
}
and I'm almost entirely certain every other part of the code compiles and runs completely fine
Have you tried to make T extend Comparable ?
Haven´t worked with Java for quite a time and don´t have an IDE here right now but I´d give it a try.
Like public boolean buildFromList(ArrayList<T extends Comparable> list) {

how to fix junit test to return value?

My data structures project on dequeues is passing all junit tests except for one. the "removeFrontRemoveRear" test. It keeps returning null instead of the
student name.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Dequeue <E> {
private int front;
private int rear;
private E[] elements;
private static final int DEFAULT_CAPACITY = 5;
/**
* Constructor sets up an empty double-ended
* queue
*/
#SuppressWarnings("unchecked")
public Dequeue() {
elements = (E[]) new Object[DEFAULT_CAPACITY];
front = 0;
rear = elements.length - 1;
}
/**
* Inserts item at the front of the dequeue. Throws
* an exception if the item could not be inserted
* #param anEntry the item to be added (Student)
* #return true
*/
public boolean addFront(E anEntry) {
if (empty()) {
front = rear = 0;
elements[front] = anEntry;
}
else if (isFull()) {
reallocate();
front = (front + (elements.length - 1)) % elements.length;
}
else {
front = (front + (elements.length - 1)) % elements.length;
}
elements[front] = anEntry;
return true;
}
/**
* private method to check if the dequeue is full
* #return true only if dequeue is full (has
* 1 empty spot)
*/
private boolean isFull() {
if (size() == elements.length -1) {
return true;
}
return false;
}
/**
*Doubles and adds 1 to the size of the dequeue
*then reallocates the data.
*/
#SuppressWarnings("unchecked")
private void reallocate() {
E[] newData = (E[]) new Object[size() * 2 + 1];
int indexOfFront = front;
for(int i = 0; i < size(); i++) {
newData[i] = elements[indexOfFront];
indexOfFront = (indexOfFront + 1) % elements.length;
}
rear = size() - 1;
front = 0;
elements = newData;
}
/**
* Inserts item at the rear of the dequeue.
* Throws an exception if the item could not be inserted
* #param anEntry the entry being inserted into the end of the queue
* #return true
*/
public boolean addRear(E anEntry) {
if (empty()) {
front = rear = 0;
elements[rear] = anEntry;
}
else if (isFull()) {
reallocate();
rear = (rear + 1) % elements.length;
}
else {
rear = (rear + 1) % elements.length;
}
elements[rear] = anEntry;
return true;
}
/**
* This method checks if the dequeue is empty
* #return true if the dequeue is empty. otherwise
* returns false
*/
public boolean empty() {
if (front == 0 && rear == elements.length-1) {
return true;
}
return false;
}
/**
* #return the dequeue's iterator
*/
public Iterator<E> iterator() {
return new dequeueIterator();
}
/**
* implementation of Iterator interface
* with inner class
*/
private class dequeueIterator implements Iterator<E> {
private int index;
private int count = 0;
/**
* references the front dequeue element
* and initializes the dequeueIterator object
*/
public dequeueIterator(){
index = front;
}
/**
*#return true it there are additional
* elements in the dequeue
*/
#Override
public boolean hasNext() {
return count < size();
}
/**
* #return the next element in the queue
*/
#Override
public E next() {
if(!hasNext()) {
throw new NoSuchElementException();
}
E returnValue = elements[index];
index = (index + 1) % elements.length;
count++;
return returnValue;
}
/**
* removes the elements accessed by the
* iterator object
*/
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* //Returns the entry at the front of the
* dequeue without removing it; returns
* NoSuchElementException if the dequeue
* is empty
* #return the object at the front of dequeue
*/
public E peekFront() {
if (empty())
throw new NoSuchElementException();
else
return elements[front];
}
/**
* returns the item at the rear of the dequeue, throws
* NoSuchElementException if empty.
* #return the element in the rear
*/
public E peekRear() {
if (empty())
throw new NoSuchElementException();
else
return elements[rear];
}
/**
*Removes the entry at the front of the dequeue and
*returns it if the dequeue is not empty. If the
*dequeue is empty, throws a NoSuchElementException
* #return front element before removing it
*/
public E removeFront() {
if (empty())
throw new NoSuchElementException();
E temp = elements[front];
elements[front] = null;
front = (front++) % elements.length;
return temp;
}
/**
* Removes the entry at the rear of the dequeue and
*returns it if the dequeue is not empty. If the
*dequeue is empty, throws a NoSuchElementException
* #return rear element before removing it
*/
public E removeRear() {
if (empty())
throw new NoSuchElementException();
E temp = elements[rear];
elements[rear] = null;
rear = (rear + elements.length - 1) % elements.length;
return temp;
}
/**
* Gets the amount of elements in the dequeue
* #return the number of elements in the dequeue
*/
public int size() {
int count = 0;
int indexOfFront = front;
int nextRearPosition = (rear + 1) % elements.length;
while(indexOfFront != nextRearPosition) {
count++;
indexOfFront = (indexOfFront + 1) % elements.length;
}
return count;
}
}
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.NoSuchElementException;
public class DequeueTest {
Dequeue<Student> q;
Student s1, s2, s3, s4, s5, s6, s7, s8;
#BeforeEach
public void setUp() throws Exception {
q = new Dequeue<Student> ();
s1 = new Student("John", "Doe");
s2 = new Student ("Jane", "Smith");
s3 = new Student ("Bob", "Taylor");
s4 = new Student ("Anne", "Frank");
s5 = new Student("Frank", "Gauvin");
s6 = new Student("Kevin", "Austin");
s7 = new Student ("Cindy", "Bryant");
s8 = new Student ("Peter", "Lander");
}
#Test
public void testaddFrontAddRear() {
q.addFront(s1);
q.addFront(s2);
q.addFront(s3);
assertThat(q.peekFront(), is(s3)); // assertEquals(s3, q.peekFront());
q.addRear(s4);
q.addRear(s5);
q.addFront(s6);
q.addRear(s7);
assertThat(q.peekRear(), is(s7)); // assertEquals(s7, q.peekRear());
assertThat(q.size(), is(7)); // assertEquals(7, q.size());
}
#Test
public void testRemoveFrontRemoveRear() {
q.addFront(s1);
q.addFront(s2);
q.addFront(s3);
q.addRear(s4);
q.addRear(s5);
q.addFront(s6);
q.addRear(s7);
assertThat(q.removeFront(), is(s6)); // assertEquals(s6, q.removeFront());
assertThat(q.removeRear(), is(s7)); // assertEquals(s7, q.removeRear());
assertThat(q.removeFront(), is(s3)); // assertEquals(s3, q.removeFront() );
assertThat(q.size(), is(4)); // assertEquals(4, q.size());
assertThat(q.removeRear(), is(s5)); // assertEquals(s5, q.removeRear());
assertThat(q.removeFront(), is(s2)); // assertEquals(s2, q.removeFront());
assertThat(q.size(), is(2)); // assertEquals(2, q.size());
assertThat(q.removeFront(), is(s1)); // assertEquals(s1, q.removeFront());
assertThat(q.removeRear(), is(s4)); // assertEquals(s4, q.removeRear());
assertTrue(q.empty());
assertTrue(q.size() == 0);
}
#Test
public void testIterator() {
q.addFront(s1);
q.addFront(s2);
q.addFront(s3);
q.addRear(s4);
assertEquals(4, q.size() );
q.addRear(s5);
q.addFront(s6);
q.addRear(s7);
assertEquals(7, q.size() );
Iterator <Student> iter = q.iterator();
ArrayList<Student> list = new ArrayList<Student>();
while (iter.hasNext()) {
list.add(iter.next() );
}
assertThat(list.get(0), is(s6)); // assertEquals(s6, list.get(0));
assertThat(list.get(1), is(s3)); // assertEquals(s3, list.get(1));
assertThat(list.get(2), is(s2)); // assertEquals(s2, list.get(2));
assertThat(list.get(3), is(s1)); // assertEquals(s1, list.get(3));
assertThat(list.get(4), is(s4)); // assertEquals(s4, list.get(4));
assertThat(list.get(5), is(s5)); // assertEquals(s5, list.get(5));
assertThat(list.get(6), is(s7)); // assertEquals(s7, list.get(6));
}
#Test
public void testPeekFrontOnEmptyQueue() throws NoSuchElementException {
assertThrows(NoSuchElementException.class, () ->
{Dequeue<Student> q = new Dequeue<Student>();
q.peekFront();});
}
#Test
public void testRearFrontOnEmptyQueue() throws NoSuchElementException{
assertThrows(NoSuchElementException.class, () ->
{Dequeue<Student> q = new Dequeue<Student>();
q.peekRear();});
}
#Test
public void testRemoveFrontOnEmptyQueue() throws NoSuchElementException {
assertThrows(NoSuchElementException.class, () ->
{Dequeue<Student> q = new Dequeue<Student>();
q.removeFront();});
}
#Test
public void testRemoveRearOnEmptyQueue() throws NoSuchElementException
{
assertThrows(NoSuchElementException.class, () ->
{Dequeue<Student> q = new Dequeue<Student>();
q.removeRear();});
}
}
/** Abstraction of a Student entity */
public class Student implements Comparable <Student> {
private String firstName;
private String lastName;
/** Initialize a Student
#param first firstName
#param last lastName
*/
public Student(String first, String last) {
firstName = first;
lastName = last;
}
/** Mutator Method
#param aName firstName
*/
public void setFirstName(String aName) {
firstName = aName;
}
/** Accessor Method
#return firstName of this Student
*/
public String getFirstName() {
return firstName;
}
/** Mutator Method
#param aName lastName
*/
public void setLastName(String aName) {
lastName = aName;
}
/** Accessor Method
#return lastName of this Student
*/
public String getLastName() {
return lastName;
}
#Override
public String toString() {
String str = "";
str += (lastName + "," + firstName);
return str;
}
/* this version overloads the equals method (note the
signature of this method).
*/
public boolean equals(Student s) {
return ( (this.lastName.equalsIgnoreCase(s.lastName)) &&
(this.firstName.equalsIgnoreCase(s.firstName)));
}
/* We need to override this method so indexOf and
contains methods work. Both of them use this version
equals method
*/
#Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
if (!(obj instanceof Student)) return false;
else {
Student s = (Student) obj;
return ( this.equals(s)); // calls the
equals(Student) method
}
}
/**
#return
a negative integer if "s1 < s2"; 0 if "s1 == s2"
a positive integer if "s1 > s2"
*/
#Override
public int compareTo(Student s) {
int result = lastName.compareToIgnoreCase(s.lastName);
if (result != 0) return result;
else
return (firstName.compareToIgnoreCase(s.firstName));
}
}
The expected result is but the actual result was null.
I am not sure what to try. I am drawing a blank. The error is brought forth in line 55 of dequeueTest.

Both methods have same erasure, yet overrides the other

I'm trying to implement a Queue but my method "enqueue(E e)" is giving me an error saying that the method clashes with the method in the Queue interface but neither override the other. What is going on?
Here is the Queue Interface
public interface Queue<E> {
/**
* Returns the number of elements in the queue.
*/
int size();
/**
* Tests whether the queue is empty.
*/
boolean isEmpty();
/**
* Inserts an element at the rear of the queue.
*/
void enqueue(E e);
/**
* Returns, but does not remove, the first element of the queue (null if empty).
*/
E first();
/**
* Removes and returns the first element of the queue (null if empty).
*/
E dequeue();
}
And here is the implementation
/**
* Implementation of the queue ADT using a fixed-length array.
* #param <E>
*/
public class ArrayQueue<E> implements Queue {
// instance variables
private E[] data;
private int f = 0;
private int sz = 0;
public static final int CAPACITY = 1000;
// Constructors
public ArrayQueue() {
this(CAPACITY);
}
public ArrayQueue(int capacity) {
data = (E[]) new Object[capacity];
}
// methods
/**
* Returns the number of elements in the queue
*/
public int size() {
return sz;
}
/**
* Tests whether the queue is empty.
*/
public boolean isEmpty() {
return sz == 0;
}
/**
* Inserts an element at the rear of the queue.
*/
public void enqueue(E e) throws IllegalStateException {
if (sz == data.length)
throw new IllegalStateException("Queue is full");
int avail = (f + sz) % data.length;
data[avail] = e;
sz++;
}
/**
* Returns, but does not remove, the first element of the queue (null if empty)
*/
public E first() {
if (isEmpty())
return null;
return data[f];
}
/**
* Removes and returns the first element of the queue (null if empty)
*/
public E dequeue() {
if (isEmpty())
return null;
E answer = data[f];
data[f] = null;
f = (f + 1) % data.length;
sz--;
return answer;
}
}
I've tried removing the "throws new IllegalStateError" and copy and pasting to make sure the spelling was the same. I can't figure out what the problem is. Both of these code fragments come straight out of a book...

Homework StackoverflowError

I'm doing some school exercises about implementing interfaces and I've already got the workspace and Test classes provided for me. What I have to do is basically implement the methods, run the Test Classes, and make sure they pass the tests.
Here is my code: http://pastebin.com/e8Vh3snC
package queue;
import java.util.*;
public class FifoQueue<E> extends AbstractQueue<E> implements Queue<E> {
private QueueNode<E> last;
private int size=0;
private FifoQueue<E> queue;
public FifoQueue() {
queue = new FifoQueue<E>();
}
/**
* Returns an iterator over the elements in this queue
* #return an iterator over the elements in this queue
*/
public Iterator<E> iterator() {
return queue.iterator();
}
/**
* Returns the number of elements in this queue
* #return the number of elements in this queue
*/
public int size() {
return size;
}
/**
* Inserts the specified element into this queue, if possible
* post: The specified element is added to the rear of this queue
* #param x the element to insert
* #return true if it was possible to add the element
* to this queue, else false
*/
public boolean offer(E x) {
if(queue.add(x)){
size++;
return true;
} else {
return false;
}
}
/**
* Retrieves and removes the head of this queue,
* or null if this queue is empty.
* post: the head of the queue is removed if it was not empty
* #return the head of this queue, or null if the queue is empty
*/
public E poll() {
if(queue.size() > 0) {
size=size-1;
}
return queue.poll();
}
/**
* Retrieves, but does not remove, the head of this queue,
* returning null if this queue is empty
* #return the head element of this queue, or null
* if this queue is empty
*/
public E peek() {
return queue.peek();
}
private static class QueueNode<E> {
E element;
QueueNode<E> next;
private QueueNode(E x) {
element = x;
next = null;
}
}
}
Here are the Test Classes, in case you want to see them (provided by the school, so I doubt they're incorrect): http://pastebin.com/uV46j0rm
package testqueue;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.NoSuchElementException;
import java.util.Iterator;
import queue.FifoQueue;
public class TestFifoQueue {
private FifoQueue<Integer> myIntQueue;
private FifoQueue<String> myStringQueue;
#Before
public void setUp() throws Exception {
myIntQueue = new FifoQueue<Integer>();
myStringQueue = new FifoQueue<String>();
}
#After
public void tearDown() throws Exception {
myIntQueue = null;
myStringQueue = null;
}
/**
* Test if a newly created queue is empty.
*/
#Test
public final void testNewFifoQueue() {
assertTrue(myIntQueue.isEmpty());
assertTrue(myIntQueue.size() == 0);
}
/** Test a single offer followed by a single peek. */
#Test
public final void testPeek() {
myIntQueue.offer(1);
int i = myIntQueue.peek();
assertEquals("peek on queue of size 1", 1, i);
assertTrue(myIntQueue.size() == 1);
}
/**
* Test a single offer followed by a single poll.
*/
#Test
public final void testPoll() {
myIntQueue.offer(1);
int i = myIntQueue.poll();
assertEquals("poll on queue of size 1", 1, i);
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
}
/**
* Test peek of empty queue.
*/
#Test
public final void testPeekOfEmpty() {
assertEquals("Front of empty queue not null", null, myIntQueue.peek());
}
/**
* Test poll of empty queue.
*/
#Test
public final void testPollOfEmpty() {
assertEquals("Poll of empty queue should return null", null, myIntQueue
.poll());
}
/**
* Test that implementation works for a queue of strings.
*/
#Test
public final void testStringQueue() {
myStringQueue.offer("First");
myStringQueue.offer("Second");
myStringQueue.offer("Third");
assertTrue("Wrong size of queue", myStringQueue.size() == 3);
assertEquals("peek on queue of strings", "First", myStringQueue.peek());
assertEquals("String First expected", "First", myStringQueue.poll());
assertEquals("String Second expected", "Second", myStringQueue.poll());
assertEquals("String Third expected", "Third", myStringQueue.poll());
assertTrue("Queue of strings should be empty", myStringQueue.isEmpty());
}
/**
* Test that polling gives elements in right order.
*/
#Test
public final void testOrder() {
myIntQueue.offer(1);
myIntQueue.offer(2);
myIntQueue.offer(3);
myIntQueue.offer(4);
myIntQueue.offer(5);
for (int i = 1; i <= 5; i++) {
int k = myIntQueue.poll();
assertEquals("poll returns incorrect element", i, k);
}
assertTrue("Queue not empty", myIntQueue.isEmpty());
}
/**
* Test that polling all elements gives an empty queue.
*/
#Test
public final void testMakeQueueEmpty() {
myIntQueue.offer(1);
myIntQueue.offer(2);
myIntQueue.poll();
myIntQueue.poll();
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
assertTrue("Queue not empty after poll", myIntQueue.isEmpty());
myIntQueue.offer(3);
myIntQueue.offer(4);
assertTrue("Wrong size after offer", myIntQueue.size() == 2);
for (int i = 3; i <= 4; i++) {
int k = myIntQueue.poll();
assertEquals("poll returns incorrect element", i, k);
}
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
assertTrue("Queue not empty after poll", myIntQueue.isEmpty());
}
}
So when I try to run the tests, I get multiple StackOverflowErrors at queue.FifiQueue.(FifoQueue.java:10)
I've been looking through the code for some hours now but can't figure out where I've written bad code.
PS: I know some of the methods are implemented incorrectly (I will try to fix them later) but as for now I'm just trying to pass the offer() och size() methods.
Your constructor is calling itself, causing infinite recursion:
public FifoQueue() {
queue = new FifoQueue<E>();
}
Maybe you mean to wrap some other type of queue or list internally?

Categories

Resources