There is a class A with one of the fields String p . The program creates an array A arr[] = new A[n] .
Is it possible to create such a method of class A to sort an array of elements of this class by the field p .
That is, it is of interest that the function call be of the form arr.sort(); , but the call was to the function of the class class A

    2 answers 2

    Your class A can implement the java.lang.Comparable interface and compare its instance with another instance in the compareTo method.

    Then you can safely use the sort method from the Arrays class.

      Himself in this area kettle. Therefore, I think that the absolutely correct answer to @Nofate can be useful to reinforce with a concrete example.

       import java.util.*; public class SortTest { public static void main (String [] av) { A [] arr = new A[4]; arr[0] = new A(12,"x12"); arr[1] = new A(16,"x16"); arr[2] = new A(1,"x1"); arr[3] = new A(62,"x62"); Arrays.sort(arr); for (A a : arr) System.out.println(a); } } class A implements Comparable { private int p; private String s; A() {} A(int v, String b) { p = v; s = b; } @Override public int compareTo(Object arg) { return p - ((A)arg).p; } public String toString() { return p+"=> "+s; } } 

      I just learn Java myself. Therefore ( here's the question for connoisseurs - why? ) Arr.sort () did not work, Eclipse says: there is no such method for arr. (Or maybe you can not write? Just do not immediately remember). Therefore, Arrays.sort (arr);

      • one
        As I understand it, sort for a class Arrays is defined as static, so a call through a class. - or8it
      • just for arrays as such in Java is not defined sorting method. But all the auxiliary buns for working with arrays are collected in the class Arrays. Naturally, all methods are static, since the class is purely utilitarian, so you do not need to create an instance of the Arrays class. - Nofate ♦