Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does operator < have a compiler error for Java generics?

Tags:

java

generics

Why does the condition key < x[mid] below cause the compiler to complain that the operator is undefined?

In C++ this would be a compile time warning only if the type T didn't support operator < semantics. How do you do the equivalent in Java?

package search;

    public class BinarySearch<T>
    {
        public boolean binary_search_iterative (T[] x, T key)
        {
            int size = x.length;
            if ( size == 0 ) { return false; }

            int end = size - 1;

            int start = 0;

            while ( start <= end)
            {
                int mid = (end + start)/2 ;
                if (key < x[mid])
                {
                    end = mid - 1;
                }
                else if ( key > key[mid])
                {
                    start = mid + 1;
                }
                else
                {
                    return true;
                }
            }

            return false;
        }
    }
like image 741
bjackfly Avatar asked Aug 08 '13 03:08

bjackfly


2 Answers

There is no operator overloading in Java. To obtain a similar result you should look into Comparable<T> which is meant to provide the same functionality to objects.

So in your case it would be:

key.compareTo(x[mid]) < 0

But to make this work you must provide a bounded type variable, T is not enough because the compiler can't infer that types what used in place of T implement Comparable so you should use:

public class BinarySearch<T extends Comparable<T>>

This because generics are not implemented like in C++ in which templates are built during compilation phase according to the types that use them. You must explicitly state what your T is because the type checker requires so.

like image 115
Jack Avatar answered Oct 30 '22 06:10

Jack


In Java you cannot overload operators.

The way this would normally be solved is to have your key class implement the Comparable<T> interface, and override its compareTo() method.

You would then limit your type parameter T to only types that implement Comparable, e.g.:

BinarySearch<T extends Comparable<T>>

And use compareTo() instead of <.

like image 20
Jason C Avatar answered Oct 30 '22 04:10

Jason C