我的Java应用程序中的Caugth ClassCastException

时间:2016-02-04 08:29:03

标签: java generics queue classcastexception generic-programming

使用数组的队列实现但是我得到了一个异常。

我有一个名为Queue的接口,它具有通用ArrayQueue作为Queue 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 */
        }
    }
}

1 个答案:

答案 0 :(得分:4)

您忽略了编译时警告。这绝不是一个好兆头。

警告基本上告诉您无法使用vmovdqa进行投射。在编译时进程中基本上会删除此强制转换并发出警告。

int s4 = (x&m4) + ((x>>1)&m4) + ((x>>2)&m4) + ((x>>3)&m4) + ((x>>4)&m4) + ((x>>5)&m4) + ((x>>6)&m4) + ((x>>7)&m4); 现在基本上在运行时成为E[]数组,并且在这样使用时,编译器在需要强制转换的地方添加类似(E)的强制转换,例如data 。 Java也会在您访问数组时执行此操作,例如Object[],这实际上是在编译期间删除了泛型的效果。

虽然java可以正确地帮助您,但它还会向您显示Integer i = (Integer)aq.dequeue();不是((Integer[])aq.data)[i]。如果java在编译时没有删除泛型,那么它会在现在出现警告的行中出错。

您应该通过提供Object[] Collections.toArray()E[] toArray(E[])

等2种方法来解决Object[]问题
相关问题