简体   繁体   中英

Defining (or overriding) Arrays.sort method

I have a class as follows.

public class MyClass{
  int x;
  String str;
  public MyClass(int x)
    {
     this.x=x;
    }
public static void main(String args[])
{
   MyClass[] myclass=new MyClass[10];
   Random rnd=new Random();
   for(int i=0;i<10;i++)
    {
      myclass[i]=new MyClass(rnd.nextInt());
     }
}
}

Now, after initializing each of the array objects, I now wish to sort it on the basis of their x values. Can Arrays.sort method be overridden to do that or I need to define my own method?

In your case, as your MyClass class obviously has a natural order, the simplest is to let it implement the Comparable interface.

After that, you can use the standard sort methods of the Arrays class .

public class MyClass implements Comparable<MyClass> {
     int x;
      ...
      @Override
        public int compareTo(MyClass o) {
            return o.x-x;
        }
    public static void main(String args[]) {
       MyClass[] myarray=new MyClass[10];
       ...
       Arrays.sort(myarray);
    }
}

There exist many overloads of Array.sort method. One of them is

public static void sort(Object[] a, int fromIndex, int toIndex, Comparator c)

Sorts the specified range of the specified array of objects according to the order induced by the specified comparator. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, the range to be sorted is empty.) All elements in the range must be mutually comparable by the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the range).

You can define a Comparator and use it.

And, because it's a static method it can't be overridden.

You can use arrays.sort to take user input and sort accordingly

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class SortMyNumbers {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String strUserInput = "";
        String strOp = "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));

        do {
            System.out
                    .println("...Enter no.s or Type End to terminate the program...");
            try {
                strUserInput = reader.readLine();

            } catch (IOException e) {
                e.printStackTrace();
            }
            if (!strUserInput.equalsIgnoreCase("end")
                    && strUserInput.contains(",")) {
                System.out.println(" Entered No.s are ..." + strUserInput);
                System.out.println("Enter no.s...");
                String strArr[] = strUserInput.split(",");

                double iArr[] = new double[strArr.length];
                int i = 0;
                // Arrays.sort(strArr);
                for (String s : strArr) {
                    iArr[i] = Double.parseDouble(s);
                    i++;
                }
                Arrays.sort(iArr);
                for (double j : iArr) {
                    strOp += String.valueOf(j) + ",";
                }
                System.out.println(" Sorted No  are " + strOp);
            } else {
                // System.out.println("Invalid i/p terminating...");
            }
            strOp = strOp.substring(0, strOp.length() - 1);

        } while (!strUserInput.equalsIgnoreCase("end"));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM