【问题标题】:Caugth ClassCastException in my Java application在我的 Java 应用程序中出现 ClassCastException
【发布时间】: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


【解决方案1】:

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

警告基本上是告诉你不能使用E[] 进行转换。这种转换基本上在编译时过程中被删除,并带有警告。

data 现在在运行时基本上变成了Object[] 数组,并且在这样的情况下使用,编译器在需要转换的地方添加转换(E),例如Integer i = (Integer)aq.dequeue();。 Java在访问数组时也会这样做,例如((Integer[])aq.data)[i],这实际上是在编译时删除了泛型的效果。

虽然 java 可以正确地帮助您,但它也向您表明 Object[] 不是 Integer[]。如果 java 在编译时没有删除泛型,它会在警告所在的行出错。

您应该通过提供Object[] Collections.toArray()E[] toArray(E[]) 等2 种方法来解决您的data 问题

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2015-03-06
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多