Chapter 9
Advanced Array Concepts

Student Learning Outcomes:
1. Sort Array Elements
2. Use two-dimensional and other multidimensional arrays
3. Use the Arrays class
4. Use the ArrayList class
5. Create enumerations

Important Points
1. Sort array elements. Process of arranging a series of objects in some logical order. Ascending 1 to infinity, A-B, descending infinity to 0, Z-A.
a. For this simple sort
temp had to be used since it is a memory address instead of a value.

††† temp=valA;† //16 goes to temp
    valA=ValB;† //2 goes to valA    
    valB=temp;† //16 goes to valB


b. to sort in ascending order based on value a being greater than
valB

    if(valA>ValB)

c. Bubble Sort - continues to compare pairs of items, swapping them if they are out of order so that the smallest items bubble to the top of list. Values must be placed in an array.

    int b, temp;
    for(b=0;b<someNum.length;++b)
        if(someNums[b]>someNums[b+1]
        {
            temp=somenums[b];
            someNums[b]=someNums[b+1];
            someNums[b+1]=temp;
        }


        You always need to pass through the list as many times as its length minus one.

d. Ascending bubble sort of the
somenums array elements.

    int comparisonsToMake=someNums.length-1;  † //this variable controls how many comparisons are made in the inner loop during each pass through the list of values.
    for (a=0,a<someNums.length-1;++a            //begin the outer loop
    {
        for(b=0;b<comparisonsToMake;++b)        //begin the inner loop
        {
            if(someNums[b] >someNums[b+1])    † //compare the two numbers
            {
                temp=someNums[b];                               
                someNums[b]=someNums[b+1];
                someNums[b+1]=temp;
            }
        }
            --comparisonsToMake; †††††††††††††† //the variable is decremented by 1 here on each pass through the list.
    }


e. Sorting Arrays of Objects: When array elements are object, you usually want to sort based on a particular object field and you typically swap entire objects and not just the field on which the comparison is  made.

    public static void bubbleSort(Employee[] array)  //shows that it receives an array of type Employee
    {
        int a, b:
        Employee temp;                       †† //temp variable is type Employee and will hold an employee object
        int highSubscript=array.length-1;       //swap each employee object empNum and salary as a unit
        for(a=0;a<highSubscript;++a)
            for(b=0;b<highSubscript;++b)
                if (array[b].getSalary()>array[b+1].getSalary())   //sort employee objects by salary
                {
                    temp=array[b];
                    array[b]=array[b+1];
                    array[b+1]=temp;
                }
    }


f. When you sort objects usually sort on a particular object field
g. When you make a swap while sorting an array of objects, you typically swap entire objects and not just the field on which the comparison is made.

2. Two-dimensional and other Multidimensional Arrays. Have two or more columns of values. Matrix or table or Spreadsheet
a. Declare an array with 3 rows and 4 columns.

††† int[][] someNumbers=new int[3][4];  

b. Initializing an array:

†   int[][] rents={{400,450,510},
    {500,560,630},    ††††††††† //this creates a 4 row 3 column array
    {625,676,740},
    {1000,1250,1600}};


c. Passing a two dimensional array to a method.

public static void displayScores(int[][]scoresArray †††† //accepts two dimensional array of int
public static Boolean areAllPricesHigh(double[][] prices) //accepts two dimensional array of doubles
public static double computerPayrollForAllEmployees(employee[][] staff) †††† //accepts two dimensional array of employee class.

Notice that the above code that the brackets are empty.  Each passed array name is a starting memory address.

d. Using length field with two dimensional arrays. The length field holds the number of rows in the array, each row has a length field that holds the number of columns in the row. Use two for loops to send data to or read data from a two dimensional array. For Example:

class DisplayRents
{
†††† public static void main(String[] args)
     {
     ††††† int[][] rents={{400,450,510},
           †††† {500,560,630},    //this creates a 4 row 3 column array
                {625,676,740},
                {1000,1250,1600}};
           int floor;
           int bdrms;
           for(floor=0;floor<rents.length;++floor)  //this determines how many rows to be read - first loop is floor 0 first row
                for(bdrms=0,bdrms<rents[floor].length;++bdrms) //this determines how may columns to be read.
                     System.out.println("Floor " + floor + //bedroom is position 0 and floor is 0 will read allbdrms in the row before going to next row.
                          " Bedrooms " + bdrms +
                          "Rent is $" + rents[floor][bdrms]);
     }
}


Output of the above is 
Floor 0 Bedrooms 0 Rent is $400 to Floor3 Bedroom 2 Rent is $1600

e. A Ragged array has rows of different lengths by declaring the number of rows but not the number of columns.

double[][] sales=new double[4][];    //array with four rows but no columns
sales[0]=new double[12];   ††††††††† //12 columns  in row 0
sales[1]=new double[18];  †††††††††† //18 columns in row 1
sales[2]=new double[9];     †††††††† //9 columns in row 2
sales[3]=new double[11];   ††††††††† //11 columns  in row 3.


f. Multidimensional arrays are any array with more than 1 dimension. In Java your can create 3, 4, 5 or more dimensions as long as you can track the order of the variables need for subscripts and you have enough memory.

3. Using the arrays class. Contains many useful methods for manipulating arrays.

Method

Purpose

static int binarySearch(type [] a, type key)

Searches the specified array for the specified key value using the binary search algorithm

static Boolean equals(type[] a, type[] a2)

Returns true if the two specified arrays of the same type are equal to one another.

static void fill(type[] a, type val)

Assigns the specified value to each element of the specified array

static void sort(type[] a)

sorts the specified array into ascending order

static void sort(type[] a, int fromIndex,int toIndex)

Sorts the specified range of the specified  array into ascending order

a. These are static methods that can be used with the class name without instantiating an Arrays object.

†† import.java.util.*; †††† //accesses the arrays class
   public class ArraysDemo
   {
      public static void main(String[] args)
      {
            int[]myScores = new int[5];                                  
†††† //construct an integer array called myScores with 5 elements
            display("Original array:                  ",myScores);    †††† //calls the display method below and displays the default 0
            Arrays.fill(myScores,8);                                       //calls the array.fill method and fills the myScores array with 8.
            display("After filling with 8s:           ",myScores);      †† //calls the display method below to display the array with 8.
            myScores[2]=6;                                                 †††† //changes myScores element 2 to 6
            myScores[4]=3;                                                 †††† //changes myScores element 4 to 3
            display("after changing two values:  ",myScores);      ††††††† //calls the display method below to display the array
††††                                                                       //with 6 in element 2k, and 3 in element 4.

            Arrays.sort(myScores);                                    †††† //calls the array.sort method and sorts the into ascending order
            display("After sorting:                      ",myScores);    † //calls the display method below and displays myScores in ascending order.
     
}
     public static void display(String message, int array[])
     {
            int sz=array.length; †††                                       //determines the array length
            System.out.print(message);                                   ††//message for first display is "Original array",
††††                                                                       //second display is "After filling with 8", third display

            for(int x=0;x<sz;++x)                                          //is "After changing two values" and forth is "After sorting". 
                System.out.print(array[x] + " ");                       †† //this prints out the contents of the array elements.
            System.out.println();                                          //this moves to the next line.
     }
  }

b. Arrays class binarySearch() provides a convenient way to search through sorted lists of values of various data types. The list must be in order before you call a binarySearch() method. Often referred to as divide and conquer.

4. Using the ArrayList Class - can be used to create containers that store lists of objects. Dynamically resizable - size can change during program execution. You add an item at any point in an arrayList container and the array will expand automatically or you can remove an item at any point and the array size will contract automatically.
a. To use an ArrayList must
import java.util.ArrayList; or import java.util.*;
b. Tto declare an ArrayList--
ArrayList names = new ArrayList();
c. Capacity is the number of items it can hold without having to increase its size. It is >= its size -
ArrayLst names=new ArrayList(20); can hold 20 names.
d. ArrayList class methods

Method

Purpose

public void add(Object)

Add an item to an ArrayList; the default version

public void add(int, Object)

Adds an item at the next available location; an overloaded version allows you to specify a position at which to add the item.

public void remove(int)

Removes an item from an ArrayList at a specified location

public void set(int, Object)

Alters an item as a specified ArrayList location

Object get(int)

Retrieves an item from a specified location in an ArrayList

public int size()

Returns the current ArrayList size.

e. names.add("Abigail") - add Abigail to the ArrayList names.
f.
names.add(0, "Bob"); - inserts Bob into element 0.
g. You will receive an error message using the methods if the position number is invalid for the specific ArrayList.
h. The size method returns the current size of the ArrayList.
i. You can sort an array list by importing the
java.util.collections package, then collections.sort(students); sorts the array list students.
j. An arraylist cannot be used to store primitive data types.
k. You must declare a reference type in the ArrayList declaration.

    String firstName;
    firstName=(String)names.get(0);† //the cast operator (String) converts the generic returned object from the get() method to a String. Must be performed.


l. The need to perform a cast can be eliminated with ArrayList objects by specifying the type that an ArrayList can hold.

††† ArrayList<String> names = new ArrayList<String>();  

This declaration provides the following advantages:
- You will not have to use the cast operator when retrieving an item from the ArrayList.
- JAVA checks to make sure that only items of the appropriate type are added to the list.
- The compiler warning that indicates our program uses an unchecked or unsafe operation is eliminated.

5. Creating Enumerations - a programmer defined data type with a fixed set of values is an enumerated data type.
a. Enumerated type examples:

††† enu Month {JAN,FEB,MAR,APR,MAY,JUNE,JULY,AUG,SEPT,NOV,DEC}; //enum constants list. Notice no "" because they are not strings but Java identifiers and must be uppercase.
    Month birthMonth;       //declared a variable named birthMonth of the enum data type month
   
birthMonth=month.MAY;   //assigns the enum constant MAY to the variable birthMonth


b. An Enumeration type like Month is a class and its enum constants act like objects instantiated from the class, including having access to the methods of the class. The built in methods
non static are below.

Method

Description

Example if birthMonth=Month.MAY

tostring()

The toString() method returns the name of the calling constant object

birthMonth.toString() has the value "MAY"

ordinal()

The ordinal() returns an integer that represents the constantís position in the list of constants: as with arrays, the first position is 0

birthMonth.ordinal() is 4

equals()

The equals() method returns true if its argument is equal to the calling objectís value.

birthMonth.equals(Month.MAY) is true
birthMonth.equals(Month.NOV) is false

compareTo()

compareTo() method returns a negative integer if the calling objects ordinal value is less than that of the argument, 0 if they are the same, and a positive integer if the callings objectís ordinal value is greater than that of the argument

birthMonth.compareTo(Month.JULY) is negative
birthMonth compareTo(Month.FEB) is positive
birthMonth compareTo(Month.MAY) is 0.

c. Some static enum methods are listed below.

Method

Description

Example with Month Enumeration

valueOf()

the valueOf() method accepts a string parameter and returns an enumeration constant

Month.valueOf("DEC") returns the DEC enum constant

values()

values() method returns an array of the enumerated constants

Month.values() returns an array with 12 elements that contain the enum constants.

d. An enumerated type may be declared in its own file in which case the filename matches the type name and has a .java extension.
e. An enumerated type can be declared within a class, but not within a method.
f. With Java 7 you can use comparison operators with enumeration constants instead of using the
compareTo() method

    if(birthMonth<Month.JUN) //here the comparison operator < less than is used.

g. Enumerations can be used to control a switch structure.
h. Enums makes the values type-safe. Type-safe describes a data type for which only appropriate behaviors are allowed.
i. Enum constants provide a form of self-documentation.
j. As with other classes you can also add methods and other fields to an enum type.