Posts

Showing posts from December 9, 2009

sort an array of object in java

Image
The java.util.Arrays class has static methods for sorting arrays, both arrays of primitive types and object types. The sort method can be applied to entire arrays, or only a particular range. For object types you can supply a comparator to define how the sort should be performed. All object types that implement Comparable (ie, defines compareTo() method), can be sorted with using a comparator. import java.util.Arrays; public class sortobjects { public static void main(String[] args) { String names[] = { "Ankit", "OM", "Deepti", "Anu" }; Arrays.sort(names); for (int i = 0; i < names.length; i++) { String name = names[i]; System.out.print("name = " + name + "; "); } Person persons[] = new Person[4]; persons[0] = new Person("Ankit"); persons[1] = new Person("OM"); persons[2] = new Person("Deepti"); persons[3] = new Person("Anu"); ...