aspose file tools*
The moose likes Java in General and the fly likes Binary search??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Binary search???" Watch "Binary search???" New topic
Author

Binary search???

Tom Barns
Ranch Hand

Joined: Oct 27, 2000
Posts: 138
Hi All
I have the following code ,I'm trying to do binary search for that specific object.but i'm getting classCastException.
please any help.
//============
import java.util.*;
class Tom
{
int i;
public Tom(int i)
{
this.i=i;
}

}
public class Search10
{
public static void main(String arg[])
{
Tom m1,m2,m3,m4,m5;
m1= new Tom(0);
m2= new Tom(1);
m3= new Tom(2);
m4= new Tom(3);
m5= new Tom(4);
Tom wi[]= new Tom[] {m1,m2,m3,m4,m5 };
try
{
System.out.println(Arrays.binarySearch(wi,m1));
}
catch(Exception e)
{
//System.out.println(e.getMessage());
e.printStackTrace();
}
}

}
//===========


Thanks for your help.
sai challa
Ranch Hand

Joined: Feb 06, 2001
Posts: 54
Hello,
You must first sort your array of Tom objectsi.e wi.
Sort the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).
Therefore your class Tom must implement the Comparable interface so that the sorting algorithm can determine how to sort the array of Tom objects.You must provide implementation of the method defined in Comparable interface.
"public int compareTo(Object o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object."
I have modified your code implementing this interface.

import java.util.*;
class Tom implements Comparable
{
int i;
public Tom(int i)
{
this.i=i;
}
public int compareTo(Object tt) {
int ii=-2;
Tom t=(Tom) tt;
if(this.i < t.i) <br /> ii=-1;<br /> else <br /> if(this.i==t.i) <br /> ii=0;<br /> else <br /> if(this.i>t.i)
ii=1;
return ii;
}
}
public class Search10
{
public static void main(String arg[])
{
Tom m1,m2,m3,m4,m5;
m1= new Tom(0);
m2= new Tom(1);
m3= new Tom(2);
m4= new Tom(3);
m5= new Tom(4);
Tom wi[]= new Tom[] {m1,m2,m3,m4,m5 };
try
{
Arrays.sort(wi);
System.out.println(Arrays.binarySearch(wi,m1));
}
catch(Exception e)
{
//System.out.println(e.getMessage());
e.printStackTrace();
}
}
}


[This message has been edited by sai challa (edited March 27, 2001).]
[This message has been edited by sai challa (edited March 27, 2001).]
Tom Barns
Ranch Hand

Joined: Oct 27, 2000
Posts: 138
Thnaks alot.
It is working.
 
 
subject: Binary search???