Java classcastexception

时间:2014-10-25 18:24:34

标签: java

System.out.println("\n1: Enter Promotion Package ID: ");
int id = sc.nextInt();
sc.nextLine();
if(PromotionDB.searchPackage(id)!=null) {
    OrderDB.createItem(id);
}

我有一个这样的代码作为我的应用程序,我想从我的PromotionDB类引用并检查ID,如果ID有效,我将ID传递给我的OrderDB类,代码:

public static void createItem(int id) {
    // TODO Auto-generated method stub
    String name = "",description = "";
    Float cost= (float) 0;

    try {
        al = readPromotion(filename) ;
        for (int i = 0 ; i < al.size() ; i++) {
            OrderForm set = (OrderForm)al.get(i);
            if(set.getid() == id){
                name = set.getname();
                description = set.getdescription();
                cost = set.getcost();
                break;
            }
        }

        OrderForm p1 = new OrderForm(id, name, description, cost);
        al.add(p1);
        savePromotionPackages(filename2, al);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("IOException > " + e.getMessage());
    }

}

但我收到了ClassCastException,有人可以向我解释原因吗?我是编程新手

1 个答案:

答案 0 :(得分:2)

您可以在文档here中了解该例外情况。

来自文档:

  

抛出以指示代码已尝试将对象强制转换为不是实例的子类。例如,以下代码生成ClassCastException:

Object x = new Integer(0);
System.out.println((String)x);

您似乎在尝试使用相同的错误:

OrderForm set = (OrderForm)al.get(i);

要修复代码,您需要readPromotion返回List<OrderForm>