【发布时间】:2018-05-23 16:32:45
【问题描述】:
您好,感谢您注意到我的问题。我想写一个可以被不同类型的数组使用的方法。但我的代码总是这样:
public int indexOf_1(int[] a,int b){
//Find the first matched result and return, otherwise report -1
int index = -1;
for(int j=0;j<a.length;j++){
if (a[j]==b)
{index=j;}
}
return index;
}
public int indexOfChar_1(char[] a,int b){
//Consider merged to the previous method?
int index = -1;
for(int j=0;j<a.length;j++){
if (a[j]==b)
{index=j;}
}
return index;
}
这似乎是多余的,我对这样的代码重复完全不满意。有没有办法为各种数组编写搜索方法以避免在这种情况下重复?谢谢!
【问题讨论】:
-
正如您在Arrays 中看到的,对于每个原始类型和对象,都必须复制代码。 BTW
if (a[j] == b) return j;会更快。 -
顺便说一句,您的代码返回数组中的 last 匹配元素,而不是第一个。要返回第一个,请将
index=j替换为return j。