【发布时间】:2018-04-20 06:41:53
【问题描述】:
我还是 Generics 的新手,我想知道为什么我不能执行“if(b[m] > key)”,这可能很简单,我太累了,没注意到。但正如你所看到的,我试图在整数数组中找到某个数字。我究竟做错了什么?它必须是通用方法。
public class Question1<T>
{
/**
* This method searches through the array of integers to check if they match the key.
* @param b array
* @param key certain number
*/
public static <T> void search(T[] b,T key)
{
int l = 0;
int r = b.length - 1;
while (l <= r)
{
int m = (l + (r-l)/2);
if(b[m].equals(key))
System.out.println("Key: " + key.toString()+ " is in Element: " + m);
if (b[m] > key)
{
l = m + 1;
}
else
{
r = m - 1;
}
}
System.out.println("Not in array.");
}
public static void main(String[] args)
{
Integer[] iray = {1,2,3,4,5};
int key = 4;
search(iray,key);
}
【问题讨论】:
-
你不能用
>比较对象。
标签: java generics computer-science