What is Arrays class in Java?

What is Arrays class in Java?

What is Arrays class in Java?

What is Arrays class in Java?

Arrays class is a utility class to define several utility methods for array objects. 

We can sort primitive arrays only based on default natural sorting order whereas we can sort object arrays either based on default natural sorting order or based on customized sorting order

Sorting elements of the array 

1 Public static void sort(primitive[] p) To sort according to the natural sorting order
2 Public static void sort(Object[] o) To sort according to the natural sorting order
3 Public static void sort(Object[] o, Comparator c) To sort according to the Customized sorting order
Example:--
package com.java4us;

import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

public class Test1 {
    public static void main(String args[]) throws IOException {
        int a[] = { 10, 20, 40, 60, 50, 80, 30 };
        System.out.println("Primitive array before sorting");
        for (int a1 : a) {
            System.out.println(a1);     //{10,20,40,60,50,80,30}
        }
        Arrays.sort(a);
        System.out.println("Primitive array before sorting");
        for (int a1 : a) {
            System.out.println(a1);     //{10,20,30,40,50,60,80}
        }
        String s[] = { "a", "b", "w", "d", "g", "u", "s" };
        System.out.println("Object array before sorting");
        for (String s1 : s) {
            System.out.println(s1);     //{a,b,w,d,g,u,s}
        }
        Arrays.sort(s);
        System.out.println("Object array after sorting");
        for (String s1 : s) {
            System.out.println(s1);     //{a,b,d,g,s,u,w}
        }
        Arrays.sort(s, new myComparator());
        System.out.println("Object array after sorting by Custom sorting");
        for (String s1 : s) {
            System.out.println(s1);     //{w,u,s,g,d,b,a}
        }
    }
}

class myComparator implements Comparator {
    public int compare(Object obj1, Object obj2) {
        String s1 = obj1.toString();
        String s2 = obj2.toString();
        return s2.compareTo(s1);
    }
}

2 comments

  1. what is array ??

Leave a Reply

Your email address will not be published. Required fields are marked *

*