Arrays and the Array list
The first subscript in an array is always ___________.
0
b. What is the subscript of the first element in the array?
0
What would the valid subscript values be in a four-element array of doubles?
0 through 3
What is the output of the following code? int[] values = new int[5]; for (int count = 0; count < 5; count++) values[count] = count +1; for (int count = 0; count < 5; count++) System.out.println(values[count]);
1 2 3 4 5
The last subscript in an array is always __________.
1 less than the number of elements
Look at the following array definition: int[] values = new int[10]; a. How many elements does the array have?
10 elements
On average, with an array of 20,000 elements, how many comparisons will the sequential search perform? (Assume the items being searched for are consistently found in the array.)
10,000 comparisons
A program has the following declaration: double[] values; Write code that asks the user for the size of the array and then creates an array of the specified size, referenced by the values variable.
// Assume keyboard references a Scanner object. int size; System.out.print("Enter the size of the array: "); size = keyboard.nextInt(); values = new double[size];
Write code that creates an ArrayList that can hold String objects. Add the names of three cars to the ArrayList, and then display the contents of the ArrayList.
// Create an ArrayList. ArrayList<String> cars = new ArrayList<String>(); // Add three car names to the ArrayList. cars.add("Porsche"); cars.add("BMW"); cars.add("Jaguar"); // Display the contents of cars. for (String str : cars) System.out.println(str);
In a program you need to store the identification numbers of ten employees (as int values) and their weekly gross pay (as double values). a. Define two arrays that may be used in parallel to store the 10 employee identification numbers and gross pay amounts.
// Define the arrays. int[] id = new int[10]; double[] weeklyPay = new double[10];
Write a loop that uses these arrays to print each of the employees' identification number and weekly gross pay.
// Display each employee's gross weekly pay. for (int i = 0; i < 10; i++) { System.out.println("The pay for employee " + id[i] + " is $" + weeklyPay[i]); }
Look at the following array definition: double[][] sales = new double[8][10]; a. How many rows does the array have? b. How many columns does the array have? c. How many elements does the array have? d. Write a statement that stores a number in the last column of the last row in the array.
8 10 80 sales[7][9] = number;
c. What is the subscript of the last element in the array?
9
int[] table = new int[10]; for (int x = 1; x <= 10; x++) { table[x] = 99; }
The loop uses the values 1 through 10 as subscripts. It should use 0 through 9.
What value in an array does the selection sort algorithm look for first? When the selection sort finds this value, what does it do with it?
The selection sort first looks for the smallest value in the array. When it finds it, it moves it to element 0.
Describe the difference between the sequential search and the binary search.
The sequential search steps through each element of the array, starting at element 0, looking for the search value. The binary search requires that the array be sorted in ascending order. It starts by looking at the middle element. If it is not the search value, and is greater than the search value, then the lower half of the array is searched next. If the middle element is not the search value, and is less than the search value, the upper half of the array is searched next. This same technique is repeated on the half of the array being searched until the element is either found or there are no more elements to search.
int[] collection = new int[-20];
The size declarator cannot be negative.
What is the difference between a size declarator and a subscript?
The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element in an array.
What is the difference between an array's size declarator and a subscript?
The size declarator specifies the number of elements in the array. A subscript identifies a specific element in the array.
What does it mean for a subscript to be out-of-bounds?
The subscript is outside the range of valid subscripts for the array.
True or False: A two-dimensional array has multiple length fields.
True
True or False: An ArrayList automatically expands in size to accommodate the items stored in it.
True
True or False: Both of the following declarations are legal and equivalent: int[] numbers; int numbers[];
True
True or False: The Java compiler does not display an error message when it processes a statement that uses an invalid subscript.
True
True or False: The subscript of the last element in a single-dimensional array is one less than the total number of elements in the array.
True
True or False: The values in an initialization list are stored in the array in the order that they appear in the list.
True
True or False: When an array is passed to a method, the method has access to the original array.
True
True or False: Java does not allow a statement to use a subscript that is outside the range of valid subscripts for an array.
Trye
Array bounds checking happens __________.
When the program runs
What happens in Java when a program tries to use a subscript that is out-of-bounds?
When the statement executes, it crashes the program and displays a runtime error message.
The values variable references a two-dimensional double array with 10 rows and 20 columns. Write code that sums all the elements in the array and stores the sum in the variable total.
double total = 0.0; // Accumulator // Sum the values in the array. for (int row = 0; row < 10; row++) { for (int col = 0; col < 20; col++) total += values[row] [col]; }
Write a statement that creates and initializes a double array with the following values: 1.7, 6.4, 8.9, 3.1, and 9.2. How many elements are in the array?
double[] array = { 1.7, 6.4, 8.9, 3.1, 9.2 }; There are five elements in the array.
b) A 25-element double array referenced by the variable payRates.
double[] payRates = new double[25];
Write code that calculates the average of all the elements in the grades array that you declared in Question 6.
final int NUM_ROWS = 30; final int NUM_COLS = 10; int total = 0; double average; for (int row = 0; row < grades.length; row++) { for (int col = 0; col < grades[row].length; col++) { total += grades[row][col]; } } average = (double) total / (NUM_ROWS * NUM_COLS);
A video rental store keeps videos on 50 racks with 10 shelves each. Each shelf holds 25 videos. Declare a three-dimensional array large enough to represent the store's storage system.
final int RACKS = 50; final int SHELVES = 10; final int VIDEOS = 25; // Create an array to hold #s int videoNumbers[][][] = new int[RACKS][SHELVES][VIDEOS];
c) A 14-element float array referenced by the variable miles.
float[] miles = new float[14];
The variable names references an integer array with 20 elements. Write a for loop that prints each element of the array.
for (int i = 0; i < 20; i++) System.out.println(names[i]);
Look at the following statements: int[] a = { 1, 2, 3, 4, 5, 6, 7 }; int[] b = new int[7]; Write code that copies the a array to the b array.
for (int i = 0; i < a.length; i++) b[i] = a[i];
A program uses a variable named array that references an array of integers. You do not know the number of elements in the array. Write a for loop that stores −1 in each element of the array.
for (int i = 0; i < array.length; i++) array[i] = -1;
Write a loop that displays the contents of each element in the array you declared in A.
for (int i = 0; i < planets.length; i++) System.out.println(planets[i]);
Write a loop that displays the first character of the strings stored in each element of the array you declared in A. (Hint: Use the String class's charAt method discussed in Chapter 2.)
for (int i = 0; i < planets.length; i++) System.out.println(planets[i].charAt(0));
Write a loop that displays the contents of each element in the array that you declared in Question 3(a).
for (int i = 0; i < scientists.length; i++) System.out.println(scientists[i]);
What import statement must you include in your code in order to use the ArrayList class?
import java.util.ArrayList;
Write code that displays the total length of all the strings in the array that you declared in Question 3(a).
int total = 0; for (int i = 0; i < scientists.length; i++) total += scientists[i].length(); System.out.println("The total length is " + total);
Write statements that create the following arrays: a) A 100-element int array referenced by the variable employeeNumbers.
int[] employeeNumbers = new int[100];
This array field holds the number of elements that the array has.
length
Look at the following method header: public static void myMethod(double[] array) Here is an array declaration: double[] numbers = new double[100]; Write a statement that passes the numbers array to the myMethod method.
myMethod(numbers);
Write a method named zero, which accepts an int array as an argument and stores the value 0 in each element.
public static void zero(int[] array) { for (int i = 0; i < array.length; i++) array[i] = 0; }
To delete an item from an ArrayList object, you use this method.
remove
Look at the following statements: int[] numbers1 = { 1, 3, 6, 9 }; int[] numbers2 = { 2, 4, 6, 8 }; int result; Write a statement that multiplies element 0 of the numbers1 array by element 3 of the numbers2 array and assigns the result to the result variable.
result = numbers1[0] * numbers2[3];
The following statement creates a BankAccount array: BankAccount[] acc = new BankAccount[10]; Is it okay or not okay to execute the following statements? acc[0].setBalance(5000.0); acc[0].withdraw(100.0);
Yes the statements are ok
How do you add items to an ArrayList object?
You use the add method.
Look at the following array definition: int[] values = { 4, 7, 6, 8, 2 }; What does each of the following code segments display? System.out.println(values[4]); x = values[2] + values[3]; System.out.println(x); x = ++values[1]; System.out.println(x);
a. 2 b. 14 c. 8
To insert an item at a specific location in an ArrayList object, you use this method.
add
This search algorithm repeatedly divides the portion of an array being searched in half.
binary search
When initializing a two-dimensional array, you enclose each row's initialization list in ___________.
braces
d) A 1000-element char array referenced by the variable letters.
char[] letters = new char[1000];
String[] words = { "Hello", "Goodbye" }; System.out.println(words.toUpperCase());
A subscript should be used with words, such as words[0].toUpperCase().
What is the difference between an ArrayList object's size and its capacity?
An ArrayList's size is the number of items stored in the ArrayList object. An ArrayList's capacity is the number of items the ArrayList object can hold without having to increase its size.
What's wrong with the following array declarations? int[] readings = new int[-1]; double[] measurements = new double[4.5];
An array's size declarator must be a non-negative integer expression. The first statement is incorrect because the size declarator is negative. The second statement is incorrect because the size declarator is a floating-point number.
Write a statement that creates an ArrayList object and assigns its address to a variable named frogs.
ArrayList frogs = new ArrayList();
Write a statement that creates an ArrayList object and assigns its address to a variable named lizards. The ArrayList should be able to store String objects only.
ArrayList<String> lizards = new ArrayList<String>();
Assuming that array1 and array2 are both array reference variables, why is it not possible to assign the contents of the array referenced by array2 to the array referenced by array1 with the following statement? array1 = array2
Because this statement merely makes array1 reference the same array that array2 references. Both variables will reference the same array. To copy the contents of array2 to array1, the contents of array2's individual elements will have to be assigned to the elements of array1.
How do you define an array without providing a size declarator?
By providing an initialization list. The array is sized to hold the number of values in the list.
How do you establish an array without providing a size declarator?
By using the same subscript value for each array
True or False: An array's sitze declarator can be a negative integer expression.
False
True or False: The first size declarator in the declaration of a two-dimensional array represents the number of columns. The second size declarator represents the number of rows.
False
How do you insert an item at a specific location in an ArrayList object?
Inserting means adding an item at a specific index. The ArrayList class has an overloaded version of the add method that allows you to add an item at a specific index.
If a sequential search method is searching for a value that is stored in the last element of a 10,000-element array, how many elements will the search code have to read to locate the value?
It will have to read all 10,000 elements to find the value stored in the last element.
If a sequential search is performed on an array, and it is known that some items are searched for more frequently than others, how can the contents of the array be reordered to improve the average performance of the search?
Move the items that are frequently searched for to the beginning of the array.
This is the typical number of comparisons performed by the sequential search on an array of N elements (assuming the search values are consistently found).
N/2
How many times will the selection sort swap the smallest value in an array with another value?
Only once.
Recall that we discussed a Rectangle class in Chapter 6. Write code that declares a Rectangle array with five elements. Instantiate each element with a Rectangle object. Use the Rectangle constructor to initialize each object with values for the length and width fields.
Rectangle[] rectArray = new Rectangle[5]; for (int i = 0; i <= rectArray.length; i++) { // Initialize each rectangle with the values // i and i+1 for length and width. rectArray[i] = new Rectangle(i, i+1); }
This search algorithm steps through an array, comparing each item with the search value.
Sequential search
To determine the number of items stored in an ArrayList object, you use this method.
Size
In an array declaration, this indicates the number of elements that the array will have.
Size declarator
Write a statement that declares a String array initialized with the following strings: "Mercury", "Venus", "Earth", and "Mars".
String[] planets = { "Mercury", "Venus", "Earth", "Mars" };
Write a statement that declares a String array initialized with the following strings: "Einstein", "Newton", "Copernicus", and "Kepler".
String[] scientists = {"Einstein", "Newton", "Copernicus", "Kepler"};
Each element of an array is accessed by a number known as a(n) __________.
Subscript
How do you retrieve a specific item from an ArrayList object?
The ArrayList class has a get method that retrieves an item at a specific index. You pass the index as an argument to the method.
How do you remove an item from an ArrayList object?
The ArrayList class has a remove method that removes an item at a specific index. You pass the index as an argument to the method.
How do you determine an ArrayList object's size?
The ArrayList class has a size method that returns the number of items stored in the ArrayList.