Example - Sorting arrays using Arrays.sort()
This example sorts an array of Strings and an array of doubles. All object types that implement Comparable (ie, defines compareTo() method), can be sorted with using a comparator. The Arrays.sort() method is also defined for primitive arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| // File : data-arrays/dblsort/Dblsrt.java // Purpose: To show how Arrays.sort() works with arrays // of both primitive and object values. // Author : Fred Swartz 2006-08-23. Public domain.
import java.util.Arrays;
public class Dblsrt { //========================================================= main public static void main(String[] args) { //... 1. Sort strings - or any other Comparable objects. String[] names = {"Zoe", "Alison", "David"}; Arrays.sort(names); System.out.println(Arrays.toString(names));
//... 2. Sort doubles or other primitives. double[] lengths = {120.0, 0.5, 0.0, 999.0, 77.3}; Arrays.sort(lengths); System.out.println(Arrays.toString(lengths)); } }
|
Output from above program
[Alison, David, Zoe]
[0.0, 0.5, 77.3, 120.0, 999.0]
0 comments:
Post a Comment