I've implemented my program but I am getting an exception java.lang.ClassCastException
This is the code:
import java.util.NoSuchElementException;
public class BasePQStack<Item> implements Stack<Item> {
// TODO: implement this object.
private int N = 0;
private MaxPQ<Compare> pq = new MaxPQ<>();
private int count;
public BasePQStack() {
count = 0;
}
/**
* entry point for sample output..
*
* @param args
*/
public static void main(String[] args) {
Stack<Integer> S = new BasePQStack<Integer>();
S.push(new Integer(2));
S.push(new Integer(7));
Integer W = S.pop();
S.push(new Integer(8));
S.push(new Integer(5));
;
Integer X = S.pop();
Integer Y = S.peek();
S.push(new Integer(3));
Integer Z = S.pop();
System.out.println("Testing: ");
System.out.println(W);
System.out.println(X);
System.out.println(Y);
System.out.println(Z);
}
@Override
public Item push(Item item) {
Compare x = new Compare(item, count);
pq.insert(x);
count++;
N++;
return item;
}
@Override
public Item pop() {
if (isEmpty())
throw new NoSuchElementException("no such element");
else {
Item var = (Item) pq.delMax();
N--;
return var;
}
}
@Override
public Item peek() {
if (isEmpty())
throw new NoSuchElementException("no such element");
else {
Item var = (Item) pq.delMax();
push(var);
return var;
}
}
@Override
public boolean isEmpty() {
return N == 0;
}
@Override
public int size() {
return N;
}
public class Compare implements Comparable<Compare> {
private Item value;
private int a;
public Compare(Item value, int a) {
this.a = a;
this.value = value;
}
@Override
public int compareTo(Compare x) {
if (this.a > x.a)
return 1;
if (this.a < x.a)
return -1;
else
return 0;
}
public int getA() {
return this.a;
}
public Item getValue() {
return this.value;
}
@Override
public String toString() {
return "item {" + "value = " + value + ",a = " + a + '}';
}
}
}
The message I am getting from the console is BasePQStack$Compare cannot be cast to java.lang.Integer. I've tried to do many castings but could not figure anything out as it just led to more error
The output of the code should be:
7
5
8
3
You should probably replace this line
Item var = (Item) pq.delMax()
With
Item var = (Item) pq.delMax().getValue();
Because delMax()
returns a compare object and you need a Item object.