I'm assuming the existence of a Widget class that implements the Comparable interface and thus has a compareTo method that accepts an Object parameter and returns an int. I want to Write an efficient static method, getWidgetMatch, that has two parameters. The first parameter is a reference to a Widget object. The second parameter is a potentially very large array of Widget objects that has been sorted in ascending order based on the Widget compareTo method. The getWidgetMatch searches for an element in the array that matches the first parameter on the basis of the equals method and returns true if found and false otherwise.
I will share two code I have almost working and my errors from debugging. Hopefully, someone has an answering I am not seeing.
Code 1:
public static boolean getWidgetMatch(Widget a, Widget[] b){
int bot=0;
int top=b.length-1;
int x = 0;
int y=0;
while (bot >= top)
{
x = (top + bot/2);
y = a.compareTo(b[x]);
if (y==0)
return true;
if (y<0)
top=x;
else
bot=x;
return false;
}
return a.equals(b[x]);
}
The debug statement for this one is this, [LWidget;@5305068a
→
false when it should be true. Am I miss a ">" sign possibly?
Code 2:
public static boolean getWidgetMatch(Widget a, Widget[] b) {
for(int i =0;i<b.length;i++){
if(b[i].compareTo(a)== 0)return true;
}
return false;
}
The debug statement for this one is this, [LWidget;@5305068a → true when it should be true and that is where I am most confused with this code.
Am I miss a "+" or "-" or a "/" sign possibly?
Thanks.