📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you will learn about the Arrays sort() method in Java programming and how to use it with an example.
1. Arrays sort() Method Overview
Definition:
The Arrays.sort() method is used to sort the elements of an array into ascending order, using the natural ordering of the array's elements or a provided comparator.
Syntax:
1. void sort(int[] a)
2. void sort(int[] a, int fromIndex, int toIndex)
3. void sort(Object[] a)
4. void sort(T[] a, Comparator<? super T> c)
Parameters:
- a: The array to be sorted.
- fromIndex: The index of the first element (inclusive) to be sorted.
- toIndex: The index of the last element (exclusive) to be sorted.
- c: The comparator to determine the order.
Key Points:
- All elements in the array must be mutually comparable.
- The sorting is stable (does not reorder equal elements).
- For primitive data types, it uses a variation of the Quicksort algorithm. For object arrays, it uses a modified mergesort.
- Throws IllegalArgumentException if fromIndex > toIndex or fromIndex and toIndex are out of bounds.
2. Arrays sort() Method Example
import java.util.Arrays;
import java.util.Comparator;
public class SortExample {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 3};
Arrays.sort(numbers);
System.out.println("Sorted numbers: " + Arrays.toString(numbers));
String[] fruits = {"Mango", "Apple", "Banana"};
Arrays.sort(fruits);
System.out.println("Sorted fruits: " + Arrays.toString(fruits));
// Using comparator for sorting in descending order
Integer[] integers = {12, 4, 8, 23, 7};
Arrays.sort(integers, Comparator.reverseOrder());
System.out.println("Sorted integers in descending: " + Arrays.toString(integers));
}
}
Output:
Sorted numbers: [1, 2, 3, 5, 8] Sorted fruits: [Apple, Banana, Mango] Sorted integers in descending: [23, 12, 8, 7, 4]
Explanation:
The Arrays.sort() method is used to sort an array in ascending order. In the example, we first sorted an array of numbers, then an array of strings using their natural order. Lastly, we sorted an array of integers in descending order by using a comparator. This showcases the versatility and usefulness of the Arrays.sort() method in different use cases.
Comments
Post a Comment
Leave Comment