我试图在各种类型的数组中返回一个特定的变量,我只能使用通用方法。但是,当我尝试执行搜索方法时,会不断出现此错误。有没有人可以给我一些想法您如何解决它?
我正在使用drjava。
这是调用语句:
System.out.printf( "%nThe item returned from integerArray is: %s",
returnItem( integerArray,
2 ) );
System.out.printf( "%nThe item returned from doubleArray is: %s",
returnItem( doubleArray,
2 ) );
System.out.printf( "%nThe item returned from characterArray is: %s",
returnItem( characterArray,
2 ) );
System.out.printf( "%nThe item returned from petArray is: %s",
returnItem( petArray,
2 ) );
这是我的搜索方法:
public static < T> int returnItem( T[ ] inputArray, int key ){
// ERROR: incompatible types: T cannot be converted to int
for ( int element : inputArray ){
if( key == element ){
return element;
}
}
return -1;
} // end method returnItem
integerArray返回的项目为:3
从integerArray返回的项目是:3.3
从integerArray返回的项目为:L
答案 0 :(得分:0)
@Noone,我建议您在构造函数中创建一个类,以预期的数据类型作为参数,将获取时间作为参数。然后您的通用退货单项或退货单项就可以了。
如果不是太多。在下面考虑我的实现:
public final class SearchAnyArray<T> {
T[] inputArray;
public SearchAnyArray(final String[] stringArray) {
inputArray = (T[]) stringArray;
}
public SearchAnyArray(final int[] integerPrimitives) {
Integer[] ints = new Integer[integerPrimitives.length];
for (int x = 0; x < integerPrimitives.length; x++) {
ints[x] = integerPrimitives[x];
}
inputArray = (T[]) ints;
}
public SearchAnyArray(final double[] doublePrimitives) {
Double[] doubles = new Double[doublePrimitives.length];
for (int x = 0; x < doublePrimitives.length; x++) {
doubles[x] = doublePrimitives[x];
}
inputArray = (T[]) doubles;
}
public SearchAnyArray(char[] charPrimitives) {
Character[] chars = new Character[charPrimitives.length];
for (int x = 0; x < charPrimitives.length; x++) {
chars[x] = charPrimitives[x];
}
inputArray = (T[]) chars;
}
public int returnItemIndex(T key) {
for (int x = 0; x < inputArray.length; x++) {
if (inputArray[x].equals(key)) {
return x;
}
}
return -1;
}
public T returnItem(int index) {
if (index < 0 || index > (inputArray.length - 1)) {
throw new ArrayIndexOutOfBoundsException("Invalid key ");
}
return inputArray[index];
}
public static void main(String[] args) {
int[] a = {1, 4, 3, 9};
double[] d = {1.0, 4.1, 3.3, 9.4};
char[] c = "ALLOWEDforReal".toCharArray();
String[] s = {"Any", "How", "Is", "a", "goal"};
System.out.println(new SearchAnyArray<>(a).returnItem(2));
System.out.println(new SearchAnyArray<>(d).returnItem(2));
System.out.println(new SearchAnyArray<>(c).returnItem(2));
System.out.println(new SearchAnyArray<>(s).returnItem(2));
System.out.println(new SearchAnyArray<>(a).returnItemIndex(3));
System.out.println(new SearchAnyArray<>(d).returnItemIndex(3.3));
System.out.println(new SearchAnyArray<>(c).returnItemIndex('L'));
System.out.println(new SearchAnyArray<>(s).returnItemIndex("Is"));
}
}```