Section 4.4. Arrays

   

4.4 Arrays

Arrays work somewhat differently in Java than in ColdFusion. To begin with, they start at zero, rather than one. Second, once created, arrays cannot be resized.

All arrays in Java are one-dimensional. You can create multidimensional arrays as you would in ColdFusion by simply storing one array as the cell value of another. Arrays can be manipulated using the java.util.Arrays class, which exposes such methods as equals() , fill() , and sort () all of which we use in upcoming code examples.

Arrays are references to objects. The arrays you create can be populated with primitive types or with references to objects.

4.4.1 Creating Arrays of Primitive Types

There are three steps to creating an array:

  1. Declare it. Write the array identifier and the type it will hold.

  2. Instantiate it. Create the array object itself with the new keyword.

  3. Initialize it. Specify the value for each variable in the array. Before you do this, arrays will be populated with the default value for the declared type.

There are actually two different ways to declare an array:

  1. type [] identifier;

    This should be familiar from main(String[] args) . Remember that spaces don' matter.

  2. type identifier [];

    An example using this syntax is main(String args []) .

The first way is preferred, and it's the one I'll generally use. It is just easier to read and understand code when it is written this way.

Once you have declared an array, the compiler does not yet know how large the array is meant to be. Because it will hold references to objects of certain types, you must declare it to be a certain size (unlike in ColdFusion). When a new array is instantiated , it is populated with the default value specified by the type of data it will hold.

Because arrays themselves are objects, you create a new array using the new keyword and the type of data it will hold:

 names = new int [10]; 

Arrays can be declared and instantiated in one statement too. The syntax is as follows :

 type [] identifier = new type [length]; 

Here is an example:

 char alphabet = new char [26]; 

Notice that you don't use the term "array"; the square brackets indicate that.

If you know in advance the specific values you want the array to hold, there is a way to do all of this work in one statement. That is, you can declare, instantiate, and initialize all at once:

 type [] identifier = {values_or_expressions}; 

Here is an example:

4.4.2 Creating Arrays of Reference Types

Creating an array of objects requires the same steps as creating an array of primitive types. You still have to declare, instantiate, and initialize them, and the syntax for doing so is the same:

 type [] identifier;  // or like this: type identifier []; 

Reference arrays are instantiated in the same manner as primitive arrays:

 identifier = new type [length]; 

They can be declared and instantiated on one line, as well:

 type [] identifier = new type [length]; 

Of course, instantiating an array of object references cannot create the objects themselves.

Arrays that hold references to objects are initialized with a default of null. A simple string example looks like this:

 String [] names = {"Bill", "Scott", "Larry", "Jeremy"}; 

Let's say that we had an object called Customer . This object defines certain properties, such as CustomerID, FirstName, Gender, and so forth. Then let's imagine that to create an object of type Customer we could either send it values for FirstName and Gender, or just leave them blank if we don't know them yet. The CustomerID will be created by some internal process. We could create an array of different Customer objects like this:

 Customer [] myCustomers = new Customer [3];       // create the objects and populate the array myCustomers[0] = new Customer(); myCustomers[1] = new Customer("Susan", 'F'); myCustomers[2] = new Customer{"Scott", 'M'); 

We could also have done this in one statement if we knew in advance what these values were going to be:

 Customer [] myCustomers = {new Customer(),      new Customer("Susan", 'F'),     new Customer{"Scott", 'M') } ; 

4.4.3 Arrays Are Objects

As mentioned before, arrays are objects, regardless of whether they hold primitive values or object references. Objects in Java have knowledge of their own states. The length of an array is therefore known to the array. The value of the length of any array is stored in the array object itself. This is necessary so that the JVM knows if you are trying to reference a cell that doesn't exist. Any attempt to reference, say, cell 50 of an array capable of holding only 25 cells throws an exception called an ArrayIndexOutOfBounds . Attempting to reference a null pointer results in a NullPointerException .

Note

Arrays in Java have an unalterable capacity. Once you state the number of cells an array will hold, you cannot change it for that array. This can be hard for ColdFusion developers to remember. It means, for instance, that you can't simply create an array without declaring the number of cells, and then add shopping cart items to it. You need to specify a number of cells in Java. As we will see, Java has many more data storage options than ColdFusion does. So it isn't a problem. In fact, it could encourage developers to write more deterministic programs.


Notice the subtle difference in the way that you can access the value of the length of strings and arrays. This is a very important difference, and understanding it now will save you a lot of hassles as you start writing programs. You can access the length of a given string by calling the String object's length() method. This method takes no parameters and is an action defined by the String class. It is called like this:

 String name = "John";  name.length(); // 4 

An array, however, stores its length as a public field. Which basically means that you reference it without parens:

 String daysOfWeek [] = new String [7];  daysOfWeek.length // 7 

The value is equal to the array length when declared. You will often make use of this property in looping, for example. The thing to notice is that () means you're making a method call and the absence of () means you are accessing a property. This can be confusing when you're getting the hang of things. The following example may make it easier to see. Let's go back to our Customer object:

 Customer.name // refers directly to the name property  Customer.getName() // calls the method that defines the                    // behavior for getting the name 

Because you very likely have to use arrays with some frequency in Cold-Fusion, there is little reason to extol their virtues here. Let's just look at some Java code examples that show you how to do the kinds of things you normally have to do, such as populating an array, reading and modifying its data, sorting, and so forth. Arrays1.java also shows how to declare and instantiate an array.

4.4.4 Arrays1.java

 /*  File: Arrays1.java      Purpose: demo use of one dimensional array, performs     various operations on the array, and outputs values  */ public class Arrays1 {     public static void main (String[] args){         // DECLARE an array that holds numbers         int [] myArray;         // INSTANTIATE it; that is, create it         // to hold a certain number of "cells"         myArray = new int [5];         /* loop over the array and output current          * values. This proves that array values are          * automatically initialized to 0.          * Remember that Java arrays start at 0--not 1          * as they do in CF.          */         for (int i = 0; i < myArray.length; i++){          System.out.print("cell #" + i + ": " + myArray[i]                      + ", ");           }         // now set values into the array.         myArray[0] = 32799;         myArray[1] = 6792;         // use random() to generate a random number         // cast to an int type, because random()         // returns a double         myArray[2] = (int) (Math.random()*100);         // just to give us some space         System.out.println();         System.out.println(myArray[2]);         // generate an error by referencing an array         // index (cell) that is outside the bounds of         // the array. In this case, that's anything         // greater than 10. In every case, that's         // anything less than 0.         // System.out.println(myArray[140]); // ERROR!         // create a new array, declaring AND instantiating         // in one statement instead of two. This one will         // hold character values and hold 26 values.         char [] letters = new char [26];         // create alphabet         String alphabet = "abcdefghijklmnopqrstuvwxyz";         for (int i = 0; i <= letters.length-1; i++){             // set value of current cell to this character             // in the alphabet             letters[i] = alphabet.charAt(i);             //output value of current array cell             System.out.print(letters[i]);         }         // output the current length of the "letters"         // array. use backslash to escape quote marks System.out.println();         System.out.println("length of the \"letters\" array "+             "is: " + letters.length);     } } 

Arrays1 , whose interspersed comments should illustrate what's happening, will show you something like this output:

 C:\jdk1.4\JavaForCF\chp4>java Arrays1  cell #0: 0, cell #1: 0, cell #2: 0, cell #3: 0, cell #4: 0, 42 abcdefghijklmnopqrstuvwxyz length of the "letters" array is: 26 

4.4.5 ArrayList s

You can work with an array as a delimited list as well. While java.util.Arrays defines an asList method, we can also use an ArrayList :

4.4.6 ArraysList.java

 import java.util.ArrayList;  public class ArraysListTest { public static void main(String[] arg) {         // create new object of ArrayList type         // call it 'a'      ArrayList a = new ArrayList();         // add items to the list.      a.add(0,"thank you");      a.add(1,"for shopping");         // we could keep going, the array will         // resize automatically like a CF array      System.out.println(a.toString());     } } 

One advantage to using an ArrayList is that you can manipulate the size of the internal array that stores the list. An ArrayList has a capacity, which is the size of the array that stores the list. The main difference, then, between an array and an ArrayList is that you can automatically grow the size of the ArrayList . This makes using an ArrayList more like using a ColdFusion array, which does not have a preset, unalterable size. An ArrayList is really a member of the set of Collections interfaces, and it is important to think of ArrayList s as Collections.

4.4.7 ArraysSearch.java

ArraysSearch.java shows you how to search and compare values inside an array.

 /* File: ArraysSearch.java  Purpose: demo Array searching & comparison Author: E Hewitt */ // import the java.util. package, which // contains the Arrays class // to handle sorting, searching, filling, and comparing. import java.util.*; public class ArraysSearch {     public static void main (String [] dude){         /* you can search a sorted array for a given key          * returns the key's index. */         // create a new array of chars         char [] myArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};         int cIndex = Arrays.binarySearch(myArray, 'e');         System.out.println(cIndex); // prints 4         // create a new character array         char [] a2 = {'l','m','n'};         // is the new array equal to the old array?         // equal here means that all elements have         // same content, in same order         boolean answer = Arrays.equals(myArray, a2);         System.out.println(answer); // false         char [] a3 = {'m','n','l'};         answer = Arrays.equals(a2, a3);         System.out.println(answer); // false         Arrays.sort(a3);         answer = Arrays.equals(a2,a3);         System.out.println(answer); // true!     } } 

Running ArraysSearch produces this output:

 4 false false true 

4.4.8 ArraysSort.java

 /* File: ArraysSort.java     Purpose: demos SORTING arrays    Date: May 5 02    Author: E Hewitt */ import java.util.*; // get the java.util.Arrays class // to handle sorting, searching, filling, and comparing. // remember that the name is case-sensitive public class ArraysSort {     public static void main (String[] args){         // declare, initialize, and instantiate         // all on the same line:         int [] IDs = {555, 333, 111, 444, 222};         // print array         for (int i = 0; i < IDs.length; i++){             System.out.println(IDs[i]);         }         System.out.println("");         // sort the array         Arrays.sort(IDs);         System.out.println(IDs[0] + "\n"); // prints 111         int start = 2;         int end = 4;         Arrays.sort(IDs, start, end); // returns void         // print the sorted array         for (int i = 0; i < IDs.length; i++) {             System.out.println(IDs[i]);             }     } } 

Running ArraysSort should give you this output:

 555 333 111 444 222 111 111 222 333 444 555 

4.4.9 ArraysFill.java

 /* File: ArraysFill.java  Purpose: demonstrate default values and filling an array with values. Author: E Hewitt */ import java.util.*; public class ArraysFill{     public static void main(String [] args){         int from = 2;         int to = 5;         // create an array         // fill its data in indexes 2, 3, and 4 with 9s         // other indexes will default to 0         int [] a;         a = new int[10];         Arrays.fill(a, from, to, 9);         System.out.println(a[2] + " " + a[0]); // prints 9 0         // be careful: java will do the math, not         // simply print the values concatenated         System.out.println(a[2] + a[3]); // prints 18         boolean [] aB = new boolean[10];         System.out.println(aB[5]);         // boolean arrays default to false;         // fill with all trues:         Arrays.fill(aB, true);         System.out.println(aB[0] + " " + aB[9]);         // remember that 9 is the last cell         // since they start at 0 instead of 1     } } 

This is the output produced by ArraysFill :

 9 0 18 false true true 

This program simply demonstrates the default values that populate an array and shows how they can be modified. It also demonstrates the return type of many operations of this sort. Populating data structures in Java often returns a boolean indicating the success of the operation, not the value inserted.

4.4.10 Multidimensional Arrays

So far we've looked at only one-dimensional arrays. There are many times, maybe when you're implementing a shopping cart or writing a nifty program that prints a series of characters in some rectangular pattern on the screen, that you need more than one dimension. Multidimensional arrays work in somewhat similar fashion to ColdFusion two- and three-dimensional arrays.

To create a two-dimensional array, just add another set of [] into the declaration:

 type [][] identifier = new type [first_size][second_size]; 

You do not have to instantiate all of the dimensions at once, but if you don't, then you must instantiate the top-level array first. For instance, this is okay:

 int a [][] = new int[4][]; // okay 

and so is this:

 int a[][] = new int[4][5]; // okay 

but this isn't:

 int a [][] = new int [][5]; // error 

Once we discuss conditional logic, we will write a sample program that puts multidimensional arrays to work.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net