【发布时间】:2016-02-04 08:29:03
【问题描述】:
使用数组的队列实现,但我遇到了异常。
我有一个名为 Queue 的接口,其中泛型 ArrayQueue 作为 Queue 接口 ArrayQueueTest 的实现类作为我的主要类来测试代码。
public interface Queue<E>
{
public void enqueue(E e);//insert an element in a queue
public E dequeue();/delete an element in queue and return that element
public int size();//give the number of elements in an queue
public E first();//give the first element of queue if any but not removing it
public boolean isEmpty();//indicate whether queue is empty or not
}
public class ArrayQueue<E> implements Queue<E>
{
E [] data; //array based implementation queue
int front; //indicating the first element of queue
int size; //size of queue indicator
ArrayQueue(int x) //initialization of queue
{
data=(E [])(new Object[x]);
}
public boolean isEmpty()
{
return size==0;
}
public int size()
{
return size;
}
public E first()
{
return data[front];
}
public E dequeue()
{
if(isEmpty())
{
System.out.println("queue is empty");
return null;
}
E ans=data[front];
data[front]=null;
front=(front+1)%data.length;
size--;
return ans;
}
public void enqueue(E e)
{
if(size==data.length)
{
System.out.println("size is full");
return;
}
data[(front+size)%data.length]=e;
size++;
}
}
public class ArrayQueueTest
{
public static void main(String[] args)
{
System.out.println("welcome");
ArrayQueue <Integer>aq=new ArrayQueue<Integer>(5);
aq.enqueue(new Integer(5));
aq.enqueue(new Integer(6));
aq.enqueue(new Integer(0));
aq.enqueue(new Integer(8));
System.out.println(aq.size());
for(int i=0;i<aq.size();i++) //loop to print the data of queue
{
// Object ob=aq.data[i]; //why i will get an exception if i did not make a comment to this line
System.out.println(aq.data[i]); /*why i am getting a ClassCastException getting at this line */
}
}
}
【问题讨论】:
-
不要忽略编译时警告,未经检查的警告提供了一些有用的信息。
-
试试这个:
System.out.println(aq.data[i].intValue());另外,如果可能的话,发布整个错误。 -
非常感谢你们摇滚!
-
不,你摇滚。但是类型擦除不会动摇。它破坏了你的 Java 代码!
标签: java generics queue classcastexception generic-programming