sort an array of object in java

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");
    Arrays.sort(persons);    //Sorts the elements of the array of a primitive type into ascending order using their natural ordering.

    for (int i = 0; i < persons.length; i++) {
      Person person = persons[i];
      System.out.println("\n\nperson = " + person);
    }
  }
}
class Person implements Comparable {
  private String name;

  public Person(String name) {
    this.name = name;
  }

  public int compareTo(Object o) {
    Person p = (Person) o;
    return this.name.compareTo(p.name);
  }
  public String toString() {
    return name;
  }
} 
The output will be:-

Comments

Popular posts from this blog

ubuntu package installation

Drupal Bootstrap Database

How to fix 500 internal privoxy error