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


why condition key < x[mid] below cause compiler complain operator undefined?

in c++ compile time warning if type t didn't support operator < semantics. how do 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 no operator overloading in java. obtain similar result should comparable<t> meant provide same functionality objects.

so in case be:

key.compareto(x[mid]) < 0 

but make work must provide bounded type variable, t not enough because compiler can't infer types used in place of t implement comparable should use:

public class binarysearch<t extends comparable<t>> 

this because generics not implemented in c++ in templates built during compilation phase according types use them. must explicitly state t because type checker requires so.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -