Using Comparator to sort an array
807589Sep 24 2008 — edited Sep 25 2008I didn't undersatnd why a comparator is used for sorting an arry in ascending order
For descending also i didn't understand the logic it follows
I have a program which works for both asc and desc using comparator
------------------------
import java.io.*;
import java.util.*;
class Ascend implements Comparator<Integer>
{
public int compare(Integer i1, Integer i2)
{
return i1.compareTo(i2);
}
}
class Descend implements Comparator<Integer>
{
public int compare(Integer i1, Integer i2)
{
return i2.compareTo(i1);
}
}
public class ArrayDemo {
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many Elements");
int size = Integer.parseInt(br.readLine());
Integer[] arr = new Integer[size];
for(int i=0 ;i<size;i++)
{
System.out.println("Enter "+(i+1)+"th element");
arr=Integer.parseInt(br.readLine());
}
Arrays.sort(arr, new Ascend());
System.out.println("The sorted array in Ascending order is:");
display(arr);
Arrays.sort(arr, new Descend());
System.out.println("The sorted array in Descending order is:");
display(arr);
}
static void display(Integer[] a)
{
for(Integer i:a)
System.out.print(i+"\t");
System.out.println("");
}
}
---------------------
can anyone explain
1 why do we are passing an object of Ascend class(code was there in above program) to Arrays.sort() method
2. what will be retruned by that object
3 why do we are passing an object of Descend class(code was there in above program) to Arrays.sort() method
4. what will be retruned by that object
5 We can sort the array in ascending simply by using Arrays.sort(arr) method directly, then what was usage of Ascend class
If I am wrong in understating the code of the above pls correct me and tell me the actual usage of Comparator<T> interfance and its method compare()
Pls....