Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

112 HOUR 9:Storing Information with Arrays


int temp = numbers[7];
numbers[5] = numbers[6];
numbers[6] = temp;

These statements result in numbers[5]and numbers[6]trading values with
each other. The integer variable called tempis used as a temporary storage
place for one of the values being swapped. Sorting is the process of arrang-
ing a list of related items into a set order, such as when a list of numbers is
sorted from lowest to highest.
Santa Claus could use sorting to arrange the order of gift recipients by last
name with Willie Aames and Hank Aaron raking in their Yuletide plunder
much earlier than alphabetical unfortunates Dweezil Zappa and Jim Zorn.
Sorting an array is easy in Java because the Arraysclass does all of the
work. Arrays, which is part of the java.utilgroup of classes, can
rearrange arrays of all variable types.
To use the Arraysclass in a program, use the following steps:


  1. Use the import java.util.*statement to make all the java.util
    classes available in the program.

  2. Create the array.

  3. Use the sort()method of the Arraysclass to rearrange an array.


An array of variables that is sorted by the Arraysclass are rearranged into
ascending numerical order. Characters and strings are arranged in alpha-
betical order.
To see this in action, create anew Empty Java File named Nameand enter
the text of Listing 9.2, a short program that sorts names, in the source editor.

LISTING 9.2 The Full Source Code of Name.java
1: importjava.util.*;
2:
3: className {
4: public static voidmain(String[] args) {
5: String names[] = { “Lauren”, “Audrina”, “Heidi”, “Whitney”,
6: “Stephanie”, “Spencer”, “Lisa”, “Brody”, “Frankie”,
7: “Holly”, “Jordan”, “Brian”, “Jason”};
8: System.out.println(“The original order:”);
9: for (int i = 0; i < names.length; i++) {
10: System.out.print(i + “: “+ names[i] + “ “);
11: }
12: Arrays.sort(names);
13: System.out.println(“\nThe new order:”);
Free download pdf