Home  >  Core Java

Example of Arrays.sort in java

By Arvind Rai, May 18, 2013
Arrays.sort sorts the array containing objects. The object must implements Comparable interface and implement compareTo. Arrays.sort sorts the array in ascending order. Find the example.
ArraySortDemo.java
package com.util;
import java.util.Arrays;
public class ArraySortDemo {
    public static void main(String[] args) {
        A a1 = new A("Ram");
        A a2 = new A("Shayam");
        A a3 = new A("Rahim");

        A[] arrA = {a1, a2, a3 };
        System.out.println("--Before Arrays.sort--");
        for (A a : arrA) {
            System.out.print(a.name + " ");
        }
        Arrays.sort(arrA);
        System.out.println("\n--After Arrays.sort--");
        for (A a : arrA) {
            System.out.print(a.name + " ");
        }
    }
}
class A implements Comparable<A> {
    public String name;
    public A(String name) {
        this.name = name;
    }
    @Override
    public int compareTo(A o) {
        return name.compareTo(o.name);
    }
}
Output
--Before Arrays.sort--
Ram Shayam Rahim
--After Arrays.sort--
Rahim Ram Shayam 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us