This question already has answers here:
Incompatible Types Error in Java
(2 answers)
Closed 9 years ago.
I'm receiving the error "type Stack does not take parameters public class ArrayStack implements Stack" from this code:
public class ArrayStack<E> implements Stack<E> {
private E[] data;
private int size;
public ArrayStack() {
data = (E[])(new Object[1]);
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public Object pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public Object peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
protected boolean isFull() {
return size == data.length;
}
public void push(Object target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
protected void stretch() {
E[] newData = (E[])(new Object[data.length * 2]);
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
}
"type Stack does not take parameters public class ArrayStack implements Stack"
The stack class is as follows.
public interface Stack<E> {
public boolean isEmpty();
public E peek();
public E pop();
public void push(E target);
}
Your peek() method should like this
public E peek() throws EmptyStructureException {
if (isEmpty()) {
throw new EmptyStructureException();
}
return (E)data[size - 1];
}
Your push() method should like this
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
Your pop() method should like this
public E pop() throws EmptyStructureException {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return (E)data[size];
}
Now your interface look like below
public interface Stack<E> {
public boolean isEmpty();
public E peek() throws EmptyStructureException;
public E pop() throws EmptyStructureException;
public void push(E target);
}
Related
For this assignment I need to create a linked stack class that contains a getMin() and getMax(). I cannot change the class header which was provided by the instructor. Both getMin and getMax should be O(1) time.
My thought is that I need to use the compareTo method to compare entries as they are pushed or poped so that I can set variables minValue and maxValue equal to their respective values. However, I don't understand the section in the class header <T extends Comparable<? super T>> nor do I know how or where to implement Comparable. I tried having my class Node<E> implement Comparable but it asked me to override the compareTo method and I'm not sure how that would work.
Any help would be greatly appreciated! Below is my code for this assignment:
public class MinMaxStack <T extends Comparable<? super T>> implements StackADT<T> {
private Node<T> top;
private int size;
public MinMaxStack() {
clear();
}
private class Node<E>{
E data;
Node<E> previous;
}
public T getMin() {
if(isEmpty()) {
throw new EmptyCollectionException("The stack is empty but is trying to getMin.");
} else {
return null;
}
}
public T getMax() {
return null;
}
#Override
public T pop() {
if(isEmpty()) {
throw new EmptyStackException("Stack is empty but trying to pop.");
}else {
T dataToReturn = top.data;
top = top.previous;
size -= 1;
return dataToReturn;
}
}
#Override
public T peek() {
if(isEmpty()) {
throw new EmptyStackException("Stack is empty but trying to peek");
}else {
return top.data;
}
}
#Override
public void push(T newItem) {
Node<T> newNode = new Node<>();
newNode.data = newItem;
if(!isEmpty()) {
newNode.previous = top;
}
top = newNode;
size += 1;
}
#Override
public int getSize() {
return size;
}
#Override
public void clear() {
while(!isEmpty()) {
top = null;
size = 0;
}
}
#Override
public boolean isEmpty() {
return size == 0;
}
}
I am writing a LinkedList implementation which includes a previous function that returns the position prior to the one passed as an input argument. It should check whether the inputted position is the first one and throw an exception in that case:
#Override
public Position<T> previous (Position<T> p) throws PositionException {
if (this.first(p)) {
throw new PositionException();
}
return this.convert(p).prev;
}
However, the following test is failing because it isn't throwing the expected exception from trying to use the previous function on the first position in the array:
#Test (expected=PositionException.class)
public void gettingPreviousAtFront() {
Position<String> one = list.insertFront("One");
Position<String> two = list.insertFront("Two");
assertTrue(list.first(two));
Position<String> beforeTwo = list.previous(two);
}
There was 1 failure: 1)
gettingPreviousAtFront(hw6.test.LinkedListTest)
java.lang.AssertionError: Expected exception:
exceptions.PositionException at
org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
It is even passing the assertion on line 301 of the test that "two" is first. So how is it possible that the exception is not being thrown by the previous function?
Here is the full linkedlist code:
package hw6;
import exceptions.EmptyException;
import exceptions.PositionException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T> implements List<T> {
private static final class Node<T> implements Position<T> {
// The usual doubly-linked list stuff.
Node<T> next; // reference to the Node after this
Node<T> prev; // reference to the Node before this
T data;
// List that created this node, to validate positions.
List<T> owner;
#Override
public T get() {
return this.data;
}
#Override
public void put(T t) {
this.data = t;
}
}
/** This iterator can be used to create either a forward
iterator, or a backwards one.
*/
private final class ListIterator implements Iterator<T> {
Node<T> current;
boolean forward;
ListIterator(boolean f) {
this.forward = f;
if (this.forward) {
this.current = LinkedList.this.sentinelHead.next;
} else {
this.current = LinkedList.this.sentinelTail.prev;
}
}
#Override
public T next() throws NoSuchElementException {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
T t = this.current.get();
if (this.forward) {
this.current = this.current.next;
} else {
this.current = this.current.prev;
}
return t;
}
#Override
public boolean hasNext() {
if (this.forward) {
return this.current != LinkedList.this.sentinelTail;
}
else {
return this.current != LinkedList.this.sentinelHead;
}
}
}
/* ** LinkedList instance variables are declared here! ** */
private Node<T> sentinelHead;
private Node<T> sentinelTail;
private int length; // how many nodes in the list
/**
* Create an empty list.
*/
public LinkedList() {
this.sentinelHead = new Node<>();
this.sentinelTail = new Node<>();
this.sentinelHead.owner = this;
this.sentinelTail.owner = this;
this.sentinelTail.prev = this.sentinelHead;
this.sentinelHead.next = this.sentinelTail;
this.length = 0;
}
// Convert a position back into a node. Guards against null positions,
// positions from other data structures, and positions that belong to
// other LinkedList objects. That about covers it?
private Node<T> convert(Position<T> p) throws PositionException {
try {
Node<T> n = (Node<T>) p;
if (n.owner != this) {
throw new PositionException();
}
return n;
} catch (NullPointerException | ClassCastException e) {
throw new PositionException();
}
}
#Override
public boolean empty() {
return this.length == 0;
}
#Override
public int length() {
return this.length;
}
#Override
public boolean first(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
return this.sentinelHead.next == n;
}
#Override
public boolean last(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
return this.sentinelTail.prev == n;
}
#Override
public Position<T> front() throws EmptyException {
if (this.length == 0) {
throw new EmptyException();
}
return this.sentinelHead.next;
}
#Override
public Position<T> back() throws EmptyException {
if (this.empty()) {
throw new EmptyException();
}
return this.sentinelTail.prev;
}
#Override
public Position<T> next(Position<T> p) throws PositionException {
if (this.last(p)) {
throw new PositionException();
}
return this.convert(p).next;
}
#Override
public Position<T> previous(Position<T> p) throws PositionException {
if (this.first(p)) {
throw new PositionException();
}
return this.convert(p).prev;
}
#Override
public Position<T> insertFront(T t) {
return this.insertAfter(this.sentinelHead, t);
}
#Override
public Position<T> insertBack(T t) {
return this.insertBefore(this.sentinelTail, t);
}
#Override
public void removeFront() throws EmptyException {
this.remove(this.front());
}
#Override
public void removeBack() throws EmptyException {
this.remove(this.back());
}
#Override
public void remove(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
n.owner = null;
n.prev.next = n.next;
n.next.prev = n.prev;
this.length--;
}
#Override
public Position<T> insertBefore(Position<T> p, T t)
throws PositionException {
Node<T> current = this.convert(p);
Node<T> n = new Node<T>();
n.owner = this;
n.data = t;
n.prev = current.prev;
current.prev.next = n;
n.next = current;
current.prev = n;
this.length++;
return n;
}
#Override
public Position<T> insertAfter(Position<T> p, T t)
throws PositionException {
Node<T> current = this.convert(p);
Node<T> n = new Node<T>();
n.owner = this;
n.data = t;
n.next = current.next;
current.next.prev = n;
n.prev = current;
current.next = n;
this.length++;
return n;
}
#Override
public Iterator<T> forward() {
return new ListIterator(true);
}
#Override
public Iterator<T> backward() {
return new ListIterator(false);
}
#Override
public Iterator<T> iterator() {
return this.forward();
}
#Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append("[");
for (Node<T> n = this.sentinelHead.next; n != this.sentinelTail; n = n.next) {
s.append(n.data);
if (n.next != this.sentinelTail) {
s.append(", ");
}
}
s.append("]");
return s.toString();
}
}
I hope that someone can help me with my little problem.
I defined my EmptyQueue and my NotEmptyQueue in this way, following my interface Immutable queue. The main problem it's that the method enQueue, that should add an element to myQueue is not working. Pls help me:
Interface:
public interface ImmutableQueue<E> extends Iterable<E> {
boolean isEmpty();
int size();
ImmutableQueue<E> enQueue(E e);
ImmutableQueue<E> deQueue();
E getTop();
}
EmptyQueue:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class EmptyQueue<E> implements ImmutableQueue <E>, Iterable <E> {
#Override
public boolean isEmpty() {
return true;
}
#Override
public int size() {
return 0;
}
#Override
public ImmutableQueue<E> enQueue(E e) {
NotEmptyQueue<E> q= new NotEmptyQueue <>(e,this);
return q;
}
#Override
public ImmutableQueue<E> deQueue() {
throw new NoSuchElementException();
}
#Override
public E getTop() {
throw new NoSuchElementException();
}
#Override
public Iterator<E> iterator() {
return new Iterator<E>(){
#Override
public boolean hasNext() {
return false;
}
#Override
public E next() {
throw new NoSuchElementException();
}
};
}
}
NotEmptyQueue:
import java.util.Iterator;
public class NotEmptyQueue<E> implements ImmutableQueue<E>, Iterable <E>{
public E e;
public ImmutableQueue<E> tail;
public NotEmptyQueue(E e, ImmutableQueue<E> tail){
this.e = e;
this.tail = tail;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public int size() {
return tail.size() + 1;
}
#Override
public ImmutableQueue<E> enQueue(E e) {
return new NotEmptyQueue<>(e,this);
}
#Override
public ImmutableQueue<E> deQueue() {
return tail;
}
#Override
public E getTop(){
return e;
}
public static void main (String [] args){
NotEmptyQueue<Integer> myQueue= new NotEmptyQueue<>(new Integer(1),null);
myQueue.enQueue(9);
myQueue.enQueue(7);
System.out.println(myQueue.size());
System.out.println(myQueue.getTop());
for(Integer i : myQueue){
System.out.println(i);
}
}
#Override
public Iterator<E> iterator() {
return new Iterator<E>(){
ImmutableQueue<E> queue;
#Override
public boolean hasNext() {
return (!tail.isEmpty());
}
#Override
public E next() {
E res = queue.getTop();
queue = queue.deQueue();
return res;
}
Iterator<E> setQueue(ImmutableQueue<E> queue){
this.queue = queue;
return this;
}
}.setQueue(this);
}
}
myQueue.enQueue(9);
should be
myQueue = myQueue.enQueue(9);
That's the usual way to deal with a persistent queue like you have.
I've been trying to turn this generic arraylist class into an array but I haven't been able to get it to work. I've hit a roadblock at the push() and pop() methods. Any help is appreciated.
Here's the original class:
public class GenericStack<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<E>();
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public E push(E o) {
list.add(o);
return o;
}
public E pop() {
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
}
And here's my revised class so far:
public class GenericStack<E> {
public static int size = 16;
#SuppressWarnings("unchecked")
private E[] list = (E[])new Object[size];
public void add(int index, E e) {
ensureCapacity();
for (int i = size - 1; i >= index; i--) {
list[i + 1] = list[i];
list[index] = e;
size++;
}
}
public int getLength() {
return list.length;
}
public E peek() {
E o = null;
o = list[0];
return o;
}
public E push(E o) {
ensureCapacity();
list.append(o);
size++;
return o;
}
public E pop() {
E o = null;
for (int i = 0; i > list.length; i++) {
o = list[i - 1];
}
list[list.length - 1] = null;
size--;
return o;
}
private void ensureCapacity() {
if (size >= list.length) {
#SuppressWarnings("unchecked")
E[] newlist = (E[])(new Object[size * 2 + 1]);
System.arraycopy(list, 0, newlist, 0, size);
list = newlist;
}
}
public boolean isEmpty() {
if (list.length > 0) {
return false;
}
else {
return true;
}
}
}
NB: You must first correct your code like mentioned in comments.
It's recommended to use name method like of official Stack class, so there are 5 methods: empty() peek() pop() push(E item) search(Object o).
You should declare initial size of your array as a constant and an other variable for current size and all your attributes should be private like that:
private final int MAX_SIZE = 16;
private int currentSize=0;
There is the code of peek() method:
public E peek() {
E o = null;
o = list[currentSize-1];
return o;
}
There is the code of push(E o) method:
public E push(E o) {
list[currentSize]=o;
currentSize++;
return o;
}
There is the code of pop() method this method must throw EmptyStackException - if this stack is empty:
public E pop() {
E o = null;
if(currentSize>0){
o=list[currentSize - 1];
list[currentSize - 1] = null;
currentSize--;
return o;
}else{
throw new EmptyStackException();
}
}
There is the code of empty() method:
public boolean empty() {
if (currentSize > 0) {
return false;
}
else {
return true;
}
}
I keep receiving an error that says that there are incompatible types. I copied this directly out of a book because we are supposed to make changes to the code to enhance the game of War. I have all of the other classes complete and compiled but this one is giving me fits. Here is the code:
public class ArrayStack<E> implements Stack<E> {
private E[] data;
private int size;
public ArrayStack() {
data = (E[])(new Object[1]);
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public Object pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public Object peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
protected boolean isFull() {
return size == data.length;
}
public void push(Object target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
protected void stretch() {
E[] newData = (E[])(new Object[data.length * 2]);
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
}
The error is occurring in the push() method at the data[size] = target; line.
EDIT:::
I'm now receiving this error.
"type Stack does not take parameters
public class ArrayStack implements Stack"
The stack class is as follows.
public interface Stack<E> {
public boolean isEmpty();
public E peek();
public E pop();
public void push(E target);
}
Change Object to E as the push() method's parameter type.
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
Likewise, you should also change the declare return type of pop() and peek() to E.
public E pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public E peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
Now your class is fully generic.
push method is not generic like the rest of the class, change it to:
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
In any case the JDK ships with the class ArrayDeque which fulfill your requirements without being a piece o code pasted from a book.
ArrayDeque<YourObj> stack = new ArrayDeque<YourObj>();
stack.push(new YourObj());
YourObj head = stack.peek();
head = stack.pop();