Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sort(Array[]a,Compare a) in class Arrays

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi All
Anyone knows how to use that method to do sorting?
actually i do not know how to deal with compare c.
it is an interface and how to supplied an argument of that type to sort method?
please any code will appreciated.
thanks
 
Hi,

You should see for Java documentation on sun's web site for better explanations, but I could tell you :

As said in the Java doc, a Comparator is a common interface for classes that provide comparison features.
The first thing to do is to create a class that implements this interface, it has to implement the following methods :
int compare(Object o1, Object o2)
Compares its two arguments for order
boolean equals(Object obj)
Indicates whether some other object is "equal to"

For example if you want to sort an array of objects which are instances of a Foo class, you might have :

public class FooComparator implements java.util.Comparator
{
public int compare (Object o1, Object o2)
{
try
{
Foo foo1 = (Foo) o1;
Foo foo2 = (Foo) o2;

//perform comparison logic for Foo instances
//return a negative integer, zero, or a
//positive integer as the first argument is
//less equal to, or greater than the second.
}
catch (Exception e) {}
...
}

public boolean equals(Object obj)
{
//for example
if (obj instanceof FooComparator)
return true;
else
return false;
}
}


Then in your code, you may have :
Foo[] array = new Foo[5];
...//fill the array
Arrays.sort (array, new FooComparator ());
...

But see the Java documentation about Comparator and Arrays, there are informations on the principles for sorting.

Hope this will help.

--
Globos
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top