Write a class, ArraySearch<E> that provides two methods: 1. static int find (E [
ID: 3550029 • Letter: W
Question
Write a class, ArraySearch<E> that provides two methods:
1. static int find (E [] haystack, E needle);
2. static int first_duplicate (E [] data);
The find method searches the haystack array to see if the elements inside are the same, which is determined by the equals method, as the needle. If the search finds a match, find returns the index that belongs to the first match. If not, find throws the exception java.util.MissingResourceException.
The method first_duplicate searches the data array to see if any two different elements of the array are the same (determined by the equals method). The return value is the index of the first duplicate found, or -1 if each of the elements of the array is unique,
**no element of the array is equal to any other element of the array**
There should be code to test your ArraySearch class.
Explanation / Answer
import java.util.MissingResourceException;
public class ArraySearch<E extends Object> {
static <E> int find(E[] haystack, E needle) throws MissingResourceException{
int foundIndex = -1;
for(int i=0; i<haystack.length; i++){
if(haystack[i].equals(needle)){
foundIndex = i;
break;
}
}
if(foundIndex!=-1){
return foundIndex;
}
else
throw new MissingResourceException("No match found in the Haystack array", "", "");
}
static <E> int first_duplicate (E [] data){
int index = -1;
boolean duplicates=false;
for (int j=0;j<data.length;j++)
for (int k=j+1;k<data.length;k++)
if (k!=j && data[k].equals(data[j])){
duplicates=true;
index = j;
}
if(duplicates)
return index;
else
return -1;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.