简体   繁体   English

使用Comparable接口时发生类强制转换异常

[英]Class cast Exception while using Comparable interface

When I am trying to execute the below code,the compiler is throwing error at line 13 as "java.lang.ClassCastException". 当我尝试执行以下代码时,编译器在第13行以“ java.lang.ClassCastException”引发错误。 Can someone let me know what's wrong with below code? 有人可以让我知道以下代码有什么问题吗?

package chapter11;

import java.util.*;

public class ComparableExample {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Item[] items = new Item[3];
        items[0] = new Item(102, "Duct Tape");
        items[1] = new Item(103, "Bailing Wire");
        items[2] = new Item(104, "Chewing Gum");

        Arrays.sort(items);
        for (Item i : items) {
            System.out.println(i.getNumber() + ":" + i.getDescription());
        }
    }
}

interface Comparable {
    int compareTo(Object o);
}

class Item implements Comparable {
    private int number;
    private String description;

    public Item(int number, String description) {
        this.number = number;
        this.description = description;
    }

    public int getNumber() {
        return number;
    }

    public String getDescription() {
        return description;
    }

    public int compareTo(Object o) {
        Item i = (Item) o;
        if (this.getNumber() < i.getNumber())
            return -1;
        if (this.getNumber() < i.getNumber())
            return 1;
        return 0;
    }
}

Any help is appreciated, Thanks!! 任何帮助表示赞赏,谢谢!

Remove your Comparable interface, and use the Comparable interface from the Java api. 删除您的Comparable接口,然后从Java api使用Comparable接口。 And also, maybe you can change 而且,也许你可以改变

public int compareTo(Object o) {
        Item i = (Item) o;
        if (this.getNumber() < i.getNumber())
            return -1;
        if (this.getNumber() < i.getNumber())
            return 1;
        return 0;
    }

into : 进入:

public int compareTo(Object o) {
            Item i = (Item) o;
            if (this.getNumber() < i.getNumber())
                return -1;
            if (this.getNumber() > i.getNumber())
                return 1;
            return 0;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM