In Java, create a generic version of the function below, there two versions one
ID: 3754780 • Letter: I
Question
In Java, create a generic version of the function below, there two versions one that takes 2 arguments (the array and the value to look for), and one that takes 4 (the array, a value, and a [lo,hi) range).
Don't forget that you cannot use == to compare the values, since that does not do the right thing for reference values.
public static boolean anyOf(int a[], int value){ // check entire array
return anyOf(a, 0, a.length, value);
}
public static boolean anyOf(int a[], int lo, int hi , int value){ // check half open
if(lo>=hi){
return false;
}else if (a[lo] == value){
return true;
}else{
return anyOf(a,lo+1,hi,value);
}
Explanation / Answer
public static boolean anyOf(T a[], T value) { // check entire array return anyOf(a, 0, a.length, value); } public static boolean anyOf(T a[], int lo, int hi, T value) { // check half open if (lo >= hi) { return false; } else if (a[lo].compareTo(value) == 0) { return true; } else { return anyOf(a, lo + 1, hi, value); } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.