Question

When I am trying to execute the below code,the compiler is throwing error at line 13 as "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!!

Was it helpful?

Solution

Remove your Comparable interface, and use the Comparable interface from the Java api. 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;
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top