You can compare by implementing Comparable
interface in your class like below.
public class Applcation {
public static void main(String[] args) {
A ary[] = {new A("D", 1),new A("C", 7),new A("K", 4),new A("L", 8),new A("S", 3)};
Arrays.sort(ary);
for (A a : ary) {
System.out.println(a.id+" - "+a.name);
}
}
}
class A implements Comparable<A>{
String name;
int id;
public A(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public int compareTo(A a) {
return this.id-a.id;
}
}
Or as an alternative you can use java 8 streams to sort your array without implementing Comparable
:
Arrays.stream(ary).sorted((a1,a2)->Integer.compare(a1.id, a2.id)).forEach(e->System.out.println(e.id+" - "+e.name));
Out-put :
1 - D
3 - S
4 - K
7 - C
8 - L