Chapter 6: Arrays and ArrayLists
Arrays of Objects
arrays as parameters
- An entire array can be passed as a parameter to a method. Because an array is an object, when an entire array is passed as a parameter, a copy of the reference to the original array is passed.
- A method that receives an array as a parameter can permanently change an element of the array because it is referring to the original element value. The method cannot permanently change the reference to the array itself because a copy of the original reference is sent to the method. These rules are consistent with the rules that govern any object type.
- An element of an array can be passed to a method as well. If the element type is a primitive type, a copy of the value is passed. If that element is a reference to an object, a copy of the object reference is passed. As always, the impact of changes made to a parameter inside the method depends on the type of the parameter.
//********************************************************************
// GradeRange.java Author: Lewis/Loftus/Cocking
//
// Demonstrates the use of an array of String objects.
//********************************************************************
public class GradeRange
{
//-----------------------------------------------------------------
// Stores the possible grades and their numeric lowest value,
// then prints them out.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-",
"D+", "D", "D-", "F"};
int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0};
for (int level = 0; level < cutoff.length; level++)
System.out.println (grades[level] + "\t" + cutoff[level]);
}
}
//********************************************************************
// NameTag.java Author: Lewis/Loftus/Cocking
//
// Demonstrates the use of command line arguments.
//********************************************************************
public class NameTag
{
//-----------------------------------------------------------------
// Prints a simple name tag using a greeting and a name that is
// specified by the user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ();
System.out.println (" " + args[0]);
System.out.println ("My name is " + args[1]);
System.out.println ();
}
}
filling arrays of objects
We must always take into account an important characteristic of object arrays: The creation of the array and the creation of the objects that we store in the array are two separate steps.
When we declare an array of String objects, for example, we create an array that holds String references. The String objects themselves must be created separately.
The String objects are created using string literals in an initializer list, or, in the case of command-line arguments, they are created by the Java runtime environment.
This issue is demonstrated in the Tunes program and its accompanying classes. Listing 6.7 shows the Tunes class, which contains a main method that creates, modifies, and examines a compact disc (CD) collection. Each CD added to the collection is specified by its title, artist, purchase price, and number of tracks.
//********************************************************************
// Tunes.java Author: Lewis/Loftus/Cocking
//
// Driver for demonstrating the use of an array of objects.
//********************************************************************
public class Tunes
{
//-----------------------------------------------------------------
// Creates a CDCollection object and adds some CDs to it. Prints
// reports on the status of the collection.
//-----------------------------------------------------------------
public static void main (String[] args)
{
CDCollection music = new CDCollection ();
music.addCD ("By the Way", "Red Hot Chili Peppers", 14.95, 10);
music.addCD ("Come On Over", "Shania Twain", 14.95, 16);
music.addCD ("Soundtrack", "The Producers", 17.95, 33);
music.addCD ("Play", "Jennifer Lopez", 13.90, 11);
System.out.println (music);
music.addCD ("Double Live", "Garth Brooks", 19.99, 26);
music.addCD ("Greatest Hits", "Stone Temple Pilots", 15.95, 13);
System.out.println (music);
}
}
The CDCollection class contains an array of CD objects representing the collection.
It maintains a count of the CDs in the collection and their combined value.
It also keeps track of the current size of the collection array so that a larger array can be created if too many CDs are added to the collection.
The collection array is instantiated in the CDCollection constructor. Every time a CD is added to the collection (using the addCD method), a new CD object is created and a reference to it is stored in the collection array.
Each time a CD is added to the collection, we check to see whether we have reached the current capacity of the collection array. If we didn’t perform this check, an exception would eventually be thrown when we try to store a new CD object at an invalid index.
If the current capacity has been reached, the private increaseSize method is invoked, which first creates an array that is twice as big as the current collection array.
Each CD in the existing collection is then copied into the new array.
Finally, the collection reference is set to the larger array. Using this technique, we theoretically never run out of room in our CD collection.
The user of the CDCollection object (the main method) never has to worry about running out of space because it’s all handled internally.
//********************************************************************
// CDCollection.java Author: Lewis/Loftus/Cocking
//
// Represents a collection of compact discs.
//********************************************************************
import java.text.NumberFormat;
public class CDCollection
{
private CD[] collection;
private int count;
private double totalCost;
//-----------------------------------------------------------------
// Creates an initially empty collection.
//-----------------------------------------------------------------
public CDCollection ()
{
collection = new CD[100];
count = 0;
totalCost = 0.0;
}
//-----------------------------------------------------------------
// Adds a CD to the collection, increasing the size of the
// collection if necessary.
//-----------------------------------------------------------------
public void addCD (String title, String artist, double cost,
int tracks)
{
if (count == collection.length)
increaseSize();
collection[count] = new CD (title, artist, cost, tracks);
totalCost += cost;
count++;
}
//-----------------------------------------------------------------
// Returns a report describing the CD collection.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "******************************************\n";
report += "My CD Collection\n\n";
report += "Number of CDs: " + count + "\n";
report += "Total cost: " + fmt.format(totalCost) + "\n";
report += "Average cost: " + fmt.format(totalCost/count);
report += "\n\nCD List:\n\n";
for (int cd = 0; cd < count; cd++)
report += collection[cd].toString() + "\n";
return report;
}
//-----------------------------------------------------------------
// Doubles the size of the collection by creating a larger array
// and copying the existing collection into it.
//-----------------------------------------------------------------
private void increaseSize ()
{
CD[] temp = new CD[collection.length * 2];
for (int cd = 0; cd < collection.length; cd++)
temp[cd] = collection[cd];
collection = temp;
}
}
//********************************************************************
// CD.java Author: Lewis/Loftus/Cocking
//
// Represents a compact disc.
//********************************************************************
import java.text.NumberFormat;
public class CD
{
private String title, artist;
private double cost;
private int tracks;
//-----------------------------------------------------------------
// Creates a new CD with the specified information.
//-----------------------------------------------------------------
public CD (String name, String singer, double price, int numTracks)
{
title = name;
artist = singer;
cost = price;
tracks = numTracks;
}
//-----------------------------------------------------------------
// Returns a description of this CD.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(cost) + "\t" + tracks + "\t";
description += title + "\t" + artist;
return description;
}
}
An Object of a Wrapper Class
Wrapper objects can be used anywhere that objects are required instead of primitive type values. For example, you can collect a sequence of floating-point numbers in an ArrayList.
Conversion between primitive types and the corresponding wrapper classes is automatic. This process is called auto-boxing (even though auto-wrapping would have been more consistent).
For example, if you assign a number to a Double object, the number is automatically “put into a box”, namely a wrapper object.
Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95);
Wrapper objects are automatically “unboxed” to primitive types.
double x = d; // auto-unboxing; same as double x = d.doubleValue();
ArrayList data = new ArrayList();
data.add(29.95);
double x = data.get(0);
The UML class diagram of the Tunes program.
Recall that the open diamond indicates aggregation (a has-a relationship). The cardinality of the relationship is also noted: a CDCollection object contains zero or more CD objects.
Classwork: Programming Projects 6.9
Homework: Programming Projects 6.6