Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generic method, runtime error,

Tags:

java

When I tried to run the code below, the compiler generates

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: JTOGenerics.ArrayCode.countGreaterThan at JTOGenerics.ArrayCode.main(ArrayCode.java:17) Java Result: 1

There is a red line beneath the line of code: int av = ArrayCode.countGreaterThan(marks, 10);

I'm new to Java and due to my limited knowledge, I tried and failed to locate the error, could someone please help me out? Many thanks in advance!!

public class ArrayCode<T> implements Comparable<T> {

    public static void main(String[] args) {
        Integer[] marks = new Integer[] {12, 0, 15, 18, 4};
        int av = ArrayCode.countGreaterThan(marks, 10);
        System.out.println("the number of Marks that are greater than 10 is: " + av);

    }

    public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
        int count = 0;
        for (T e : anArray) {
            if (((Comparable<T>)e).compareTo(elem) > 0) {
                ++count;
            }
        }
        return count;
    }

    @Override
    public int compareTo(T o) {
        if (this.equals(o)) {
            return 1;
        } else {
            return 0;
        }
    }

    public interface Comparable<T> {

        public int compareTo(T o);
    }
}
like image 865
Jess Avatar asked Feb 09 '23 14:02

Jess


2 Answers

You've defined your own Comparable interface within the ArrayCode class. It appears that the type bound for the generic static method countGreaterThan is resolving to that Comparable interface. However, Integer implements the built-in java.lang.Comparable interface instead.

Remove your own Comparable interface, which means Comparable will refer to the built-in Comparable interface.

In addition, the ArrayCode class doesn't need to implement Comparable itself (unless there is other non-static code that we aren't seeing in your post); you can remove implements Comparable<T> on ArrayCode, ArrayCode's own T type parameter, and ArrayCode's compareTo method also. Plus, you don't need the cast to Comparable<T> in the if condition; it's unnecessary.

like image 66
rgettman Avatar answered Feb 16 '23 04:02

rgettman


It's because you've created your own interface called Comparable.

Integer does not implement your version.

I would just get rid of your version.

like image 28
Paul Boddington Avatar answered Feb 16 '23 02:02

Paul Boddington