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
MyClassclass 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.