Sorting arrays and Length of an Array


Sorting arrays

Sorting arrays can be easily done with the Arrays api.

import java.util.Arrays;
 
int[] numbers = {45, 12, 77, 34, 90};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Prints sorted array

Sorting String arrays:

String is not a numeric data, it defines it's own order which is called lexicographic order, also known as alphabetic order. When you sort an array of String using sort() method, it sorts array into natural order defined by Comparable interface, as shown below :

Increasing Order

String[] animals = {"Elephant", "Tiger", "Lion", "Giraffe", "Zebra"};
System.out.println("String array before sorting : " + Arrays.toString(animals));
Arrays.sort(animals);
System.out.println("String array after sorting in ascending order : " + Arrays.toString(animals));

Output

String array before sorting : [Elephant, Tiger, Lion, Giraffe, Zebra]
String array after sorting in ascending order : [Elephant, Giraffe, Lion, Tiger, Zebra]

Decreasing Order

String[] words = {"apple", "banana", "orange", "grape"};
Arrays.sort(words, 0, words.length, Collections.reverseOrder());
System.out.println("String array after sorting in descending order: " + Arrays.toString(words));

Output

String array after sorting in descending order: [orange, grape, banana, apple]

Sorting an Object array

In order to sort an object array, all elements must implement either Comparable or Comparator interface to define the order of the sorting.

We can use either sort(Object[]) method to sort an object array on its natural order, but you must ensure that all elements in the array must implement Comparable.

Furthermore, they must be mutually comparable as well, for example e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array. Alternatively you can sort an Object array on custom order using sort(T[], Comparator) method as shown in following example.

Course[] subjects = new Course[3];
subjects[0] = new Course(101, "Math", 150);
subjects[1] = new Course(201, "Physics", 300);
subjects[2] = new Course(301, "Biology", 200);
 
System.out.println("Object array before sorting : " + Arrays.toString(subjects));
 
Arrays.sort(subjects);
System.out.println("Object array after sorting in natural order : " + Arrays.toString(subjects));
 
Arrays.sort(subjects, new Course.PriceComparator());
System.out.println("Object array after sorting by price : " + Arrays.toString(subjects));
 
Arrays.sort(subjects, new Course.NameComparator());
System.out.println("Object array after sorting by name : " + Arrays.toString(subjects));

Output

Object array before sorting : [Course{id=101, name='Math', price=150}, Course{id=201, 
name='Physics', price=300}, Course{id=301, name='Biology', price=200}]
Object array after sorting in natural order : [Course{id=101, name='Math', price=150}, 
Course{id=201, name='Physics', price=300}, Course{id=301, name='Biology', price=200}]
Object array after sorting by price : [Course{id=101, name='Math', price=150}, Course{id=301, 
name='Biology', price=200}, Course{id=201, name='Physics', price=300}]
Object array after sorting by name : [Course{id=301, name='Biology', price=200}, Course{id=201, 
name='Physics', price=300}, Course{id=101, name='Math', price=150}]
 

Getting the Length of an Array

Arrays are objects which provide space to store up to its size of elements of specified type. An array's size can not be modified after the array is created.

int[] arr1 = new int[0];
int[] arr2 = new int[2];
int[] arr3 = new int[]{1, 2, 3, 4};
int[] arr4 = {1, 2, 3, 4, 5, 6, 7};
int len1 = arr1.length; // 0
int len2 = arr2.length; // 2
int len3 = arr3.length; // 4
int len4 = arr4.length; // 7

The length field in an array stores the size of an array. It is a final field and cannot be modified.

This code shows the difference between the length of an array and amount of objects an array stores.

public static void main(String[] args) {
    Integer values[] = {4, null, 7, 2, null, null, 10, 5, null};
    int valuesLength = values.length;
    int nonNullCount = 0;
 
    for (int i = 0; i < valuesLength; i++) {
        Integer value = values[i];
        if (value != null) {
            nonNullCount++;
        }
    }
 
    System.out.println("The array 'values' has a length of " + valuesLength + "\n"
            + "and it contains " + nonNullCount + " non-null values");
}

Output

The array 'values' has a length of 9
and it contains 5 non-null values

Basic Programs