So lets see how to sort an array using java Arrays class.
here is the coding example.
import java.util.Arrays; public class ArraySort { public static void main (String[] args){ String[] names = { "Nimal", "Sunil", "Tharaka", "Isuru","Anuradha"}; int[] intNumbers = { 3, 5, 12, 7, 1, 9}; double[] doubleNumbers = { 2.34, 45.213, 4.76, 4.23, 8.32}; //sorting String array 'names' Arrays.sort(names); int i=1; System.out.println("After sorting String array"); for(String name:names) System.out.println("item"+i+++" - "+name); //sorting int array 'intNumbers' Arrays.sort(intNumbers); i=1; System.out.println("After sorting int array"); for(int num:intNumbers) System.out.println("item"+i+++" - "+num); //sorting double array 'doubleNumbers' Arrays.sort(doubleNumbers); i=1; System.out.println("After sorting double array"); for(double num:doubleNumbers) System.out.println("item"+i+++" - "+num); } }
Output for this code will be like this.
After sorting String array
item1 - Anuradha
item2 - Isuru
item3 - Nimal
item4 - Sunil
item5 - Tharaka
After sorting int array
item1 - 1
item2 - 3
item3 - 5
item4 - 7
item5 - 9
item6 - 12
After sorting double array
item1 - 2.34
item2 - 4.23
item3 - 4.76
item4 - 8.32
item5 - 45.213
This Arrays.sort() method support not only for String, int and double arrays but also for byte, char, long, float and object arrays
No comments:
Post a Comment