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
//******************************************************************** // 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); } }
//******************************************************************** // 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.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