使用数组的队列实现,但我遇到了异常。
我有一个名为 Queue 的接口(interface),其中通用 ArrayQueue 作为队列接口(interface) 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 */
}
}
}
最佳答案
您正在忽略编译时警告。这绝不是一个好兆头。
警告基本上告诉您不能使用 E[]
进行转换。这种转换在编译时过程中基本上被删除,并带有警告。
data
现在在运行时基本上变成了一个 Object[]
数组,并且在这种情况下使用,编译器在需要强制转换的地方添加像 (E) 这样的强制转换,例如 Integer i = (Integer)aq.dequeue();
。 Java 在访问数组时也会这样做,例如 ((Integer[])aq.data)[i]
,这实际上是在编译期间删除泛型的效果。
虽然 java 可以正确帮助您,但它也向您表明 Object[]
不是 Integer[]
。如果 java 在编译时没有删除泛型,它会在现在警告所在的行出错。
您应该通过提供 2 种方法来解决您的 data
问题,例如 Object[] Collections.toArray()
和 E[] toArray(E[])
关于java - 在我的 Java 应用程序中发现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35195986/