Search code examples
javaoopgenericscomparatorcomparable

Generics and Comparable and Comparator... Syntax error, insert ";" to complete LocalVariableDeclarationStatement"


This question deals with generics and using the Comparable and Comparator interfaces.

I have a class Chocolate:

public class Chocolate implements Comparable<Chocolate> {

    public int compareTo(Chocolate c) {
        if (this.getValue() > c.getValue()) {
            return 1;
        } else if (this.getValue() < c.getValue()) {
            return -1;
        } else {
            return 0;
        }
    }
}

and a class Pair

public abstract class Pair<E extends Comparable<E>, T extends Comparable<T>>
    implements Comparable<Pair<E, T>> { 

    public int compareTo(Pair<E, T> p) {
        if (this.first.compareTo(p.first) > 0) {
            return 1;
        } else if (this.first.compareTo(p.first) < 0) {
            return -1;
        } else {
            if (this.second.compareTo(p.second) > 0) {
                return 1;
            } else if (this.second.compareTo(p.second) < 0) {
                return -1;
            }
        }
        return 0;
    }
}

And another class Sorter with a main method

public class SortingClient {

    public static void main(String[] args){

        Pair<Chocolate, Chocolate>[] pairs = (Pair<Chocolate, Chocolate>[]) new Pair<?,?>[numPairs];

        Comparator<Pair<Chocolate, Chocolate>> interfaceChocolate = new Comparator<Pair<Chocolate, Chocolate>>(){
            public int compare(Pair<Chocolate,Chocolate> c1, Pair<Chocolate,Chocolate> c2){
                if (c1.compareTo(c2) > 0){
                    return 1;
                }
                else if (c1.compareTo(c2) < 0){
                    return -1;
                }
                else {
                    return 0;
                }
            }
        } * Error here*
    }

I get an Error at the second to last line marked saying "Syntax error, insert ";" to complete LocalVariableDeclarationStatement" What does this error mean, and how can I fix it?


Solution

  • You always need a semicolon to end a variable declaration, even if you are creating an instance of an anonymous class.

    If you had for example a concrete class PairChocolateComparator, you would still use a semicolon:

    Comparator<Pair<Chocolate, Chocolate>> interfaceChocolate =
        new PairChocolateComparator<Pair<Chocolate, Chocolate>>();
    

    So you should still add the semicolon for the anonymous class instance:

    Comparator<Pair<Chocolate, Chocolate>> interfaceChocolate =
        new Comparator<Pair<Chocolate, Chocolate>>(){
             // body omitted
    };