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;
}
}
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.
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 <
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With