Dhruv
Dhruv

Reputation: 21

Java: Runtime ClassCastException using Priority Queue & custom class?

import java.util.*;
public class Lab72 {
    public static void main(String[] args) {
        Queue que= new PriorityQueue();
        que.add(new Hello(3));
        que.add(new Hello(23));
        que.add(new Hello(7));
        que.add(new Hello(67));
        que.add(new Hello(39));
        System.out.println(que);

        class Hello implements Comparable {
            int x;

            Hello(int x){
                this.x=x;
            }

            public String toString() {
                return "" + x;
            }

            public int compareTo(Object obj) {
                if(obj instanceof Hello) {
                    Hello h1= (Hello)obj;
                    return this.x-h1.x;
                }
                return 0;
            }
        }
    }
}

I am getting the following error during Runtime:

 Exception in thread "main" java.lang.ClassCastException:     Hello       cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at java.util.PriorityQueue.add(Unknown Source)
at Lab72.main(Lab72.java:6)

Line 6 is que.add(new Hello(23));

Is there anything wrong with the usage of constructor? Since Hello is a custom class, I have provided with Comparable interface, compareTo() and toString() methods both are overridden.

Upvotes: 1

Views: 151

Answers (1)

Eran
Eran

Reputation: 393986

You shouldn't be using raw types.

Try:

class Hello implements Comparable<Hello>
{
    int x;
    Hello(int x){
        this.x=x;
    }
    public String toString() {
        return ""+x;
    }
    public int compareTo(Hello obj) {
        return this.x-obj.x;
    }
}

Also change

Queue que= new PriorityQueue();

to

Queue<Hello> que= new PriorityQueue<Hello>();

Upvotes: 4

Related Questions