Java Array problems, Java Arrays, Java Chapter 6
int[] age = {2, 12, 1};
Initialize the array age integer values with values of 2, 12, 1
for (index = 0; index < reading.length; index++) reading[index] = 42.0;
Initialize the array reading to all 42.0 using for loop double[] reading = new double[100]; int index;
n log n, n, n^2
List selection sort in order of fastest to slowest n , n^2, n log n
variable
Method with a ________________ number of parameters.
What makes an array list different from an array?
Only holds objects. Can grow and shrink as needed. Supplies methods for inserting and removing objects. More overhead.
What is regression testing?
Regression testing involves repeating previously run tests to ensure that known failures of prior versions do not appear in new versions of the software.
What does this do? System.arraycopy(data, i + 1, data, i, data.length - i - 1);
Removes an element at position i.
Multidimensional Array
Represents a __________________________ double[][]table = new double[100][10]; int[][][] figure = new int[10][20][30];
int i; for (i = 0; (i < a.length) && (i < b.length); i++) b[i] = a[i]; (create an alias effectively)
The following code will make two different arrays have the same values in each _____________ position
This method is legal but pointless. When invoked, it has no effect on its argument. The parameter a is a local variable that contains a reference. The reference does indeed get changed so it refers to an array of double the size of the argument, but that reference goes away when the method ends. A method can change the values of the indexed variables of its argument, but it cannot change the reference in the array variable used as an argument.
The following method definition will compile but does not work as you might hope. What is wrong with it? public static void doubleSize(int[] a) { a = new int[a.length * 2]; }
for (ArrayBaseType VariableName : ArrayName) Statement Example: for (int i = 0; i < a.length; i++) a[i] = 0.0; Can be changed to: for (double element : a) element = 0.0;
The general syntax for a for-each loop statement used with an array is
indexed
The individual variables that together make up the array are called __________ variables.
What field returns the number of elements in an array?
The length field. It is an instance variable of the array.
nonexistent
The most common programming error made when using arrays is to attempt to access a _________________array index. Always check the first and last iterations of a loop that manipulates an array to make sure it does not use an index that is illegally small or illegally large.
True
True or False All of the indexed variables in a single array must be of the same type, called the base type of the array
What are parallel arrays?
Two different arrays that should be combined into one array containing objects.
What is a 2D array?
Two-dimensional arrays form a tabular, two-dimensional arrangement. You access elements with an index pair a[i][j].
Single dimensional array Multi dimensional arrays
Types of Arrays
What does System.arraycopy do?
Use the System.arraycopy method to copy elements from one array to another.
How do you copy the elements of an array?
Use the clone method to copy the elements of an array. Has a return type of Object.
How to find the number of elements in: a) an Array b) an ArrayList c) a String
a) .length b) .size() c) .length()
Example of for low for 2 dim array
int row, column; for (row = 0; row < page.length; row++) for (column = 0; column < page[row].length; column++) page[row][column] = 'Z';
Initialize an integer array named primes with five values.
int[] primes = new int[] { 2, 3, 5, 7, 11 };
Syntax for initializing an array
typeName[] arrayReference = new typeName[length] Ex. double[] data = new double[10];
array
An ________ can be used to store and manipulate a collection of data that is all of the same type.
enumerated
An _____________ type is a type in which all the values are given in a (typically) short list
instance variable
An ________________ of a class can be of an array type.
Definition of an array
An array is a sequence of values of the same type. They can hold both primitives and objects.
ragged
An array that has a different number of elements per row it is called a ______________ array
What does an array variable do?
An array variable stores a reference to the array. Copying the variable yields a second reference to the same array.
new
Arrays are objects that are created with ________ just like the class objects we discussed before this chapter (although there is a slight difference in the syntax used).
What does this do? double[] data = new double[10]; . . . // Fill array double[] prices = data;
Both arrays are now pointing to the same reference.
public void myMethod(int[][] a)
Call myMethod using a[] [] interger type
It should not
Can an indexed variable that has not been given a meaningful value in a partial array ever be referenced?
/** Precondition: numberUsed <= argumentArray.length; the first numberUsed indexed variables of argumentArray have values. Returns an array of length numberUsed whose ith element is argumentArray[i] adjustment. */ public static double[] differenceArray( double[] argumentArray, int numberUsed, double adjustment) { double[] temp = new double[numberUsed]; for (int i = 0; i < numberUsed; i++) temp[i] = argumentArray[i] - adjustment; return temp; }
Complete the definition of the following method that could be added to the class GolfScores in Display 6.4: /** Precondition: numberUsed <= argumentArray.length; the first numberUsed indexed variables of argumentArray have values. Returns an array of length numberUsed whose ith element is argumentArray[i] - adjustment. */ public static double[] differenceArray( double[] argumentArray, int numberUsed, double adjustment)
int[] array = new int[10];
Create a new array
char[][] a = new char[5][12];
Declare a two dimensional array called a of type character with length 5 and 12
equalsArray
Do you use == to compare an array or equalsArray
Two dimensional array a [5][12]
Example of:
Ragged Array
Example of: double [][] a; a = new double[3][]; Since the above line does not specify the size of a[0], a[1], or a[2], each could be made a different size instead:
a) word b) String c) 5 d) 0 through 4 inclusive e) Any of the following would be correct: word[0], word[1], word[2], word[3], word[4]
1. In the array declaration String[] word = new String[5]; what is a) the array name? b) the base type? c) the length of the array? d) the range of values an index accessing this array can have? e) one of the indexed variables (or elements) of this array?
SomeClass.doSomething(number); //Legal. SomeClass.doSomething(a[2]); //Legal. SomeClass.doSomething(a[3]); //Illegal. Index out of bounds. SomeClass.doSomething(a[number]); //Legal. SomeClass.doSomething(a); //Illegal.
7. Consider the following class definition: public class SomeClass { public static void doSomething(int n) { <Some code goes in here.> } <The rest of the definition is irrelevant to this question.> Which of the following are acceptable method calls? int[] a = {4, 5, 6}; int number = 2; SomeClass.doSomething(number); SomeClass.doSomething(a[2]); SomeClass.doSomething(a[3]); SomeClass.doSomething(a[number]); SomeClass.doSomething(a);
method
A ______________ may return an array as the value returned by the ______________.
array
A method can have parameters of an _____________ type. When the method is invoked, an entire ___________ is plugged in for the array parameter.
for (int index = 0; index < count; index++) Place the indexth smallest element in a[index]
A selection sort accomplishes this by using the following algorithm:
What is a test suite?
A test suite is a set of tests for repeated testing.
What does this do? System.arraycopy(data, i, data, i + 1, data.length - i - 1); data[i] = x;
Adds a new element at position i into data, first moves all elements from i onward one position up. Then inserts the new value. Last element is lost.
public ClassType[] getArray() { ClassType[] temp = new ClassType[count]; for (int i = 0; i < count; i++) temp[i] = new ClassType(someArray[i]); return temp; }
Fix Privacy Leak public double[] getArray() { double[] temp = new double[count]; for (int i = 0; i < count; i++) temp[i] = a[i]; return temp }
Square brackets can be used to create a type name: double[] score; Square brackets can be used with an integer value as part of the special syntax Java uses to create a new array: score = new double[5]; Square brackets can be used to name an indexed variable of an array: max = score[0];
Give the Three Ways to Use Square Brackets [] with an Array Name
public static double[] halfArray(double[] a) { double[] temp = new double[a.length]; for (int i = 0; i < a.length; i++) temp[i] = a[i]/2.0; return temp; }
Give the definition of a method called halfArray that has a single parameter for an array of base type double and that returns another array of base type double that has the same length and in which each element has been divided by 2.0. Make it a static method. To test it, you can add it to any class or, better yet, write a class with a test program in the method main.
The last value of index is a.length - 1, which is the last index of the array. However, when index has the value a.length - 1, a[index + 1] has an index that is out of bounds because index + 1 is one more than the largest array index. The for loop ending condition should instead be index < a.length - 1.
However, to be safe we want our program to test the array and issue a warning in case it turns out that some elements are out of order. The following code is supposed to output such a warning, but it contains a bug. What is the bug? double[] a = new double[10]; <Some code to fill the array a goes here.> for (int index = 0; index < a.length; index++) if (a[index] > a[index + 1]) System.out.println("Array elements " + index + " and " + (index + 1) + " are out of order.");
multidimensional array
If you need an array with more than one index, you can use a ____________________, which is actually an array of arrays.
False In Java, a method may also return an array - The return type is specified in the same way that an array parameter is specified public static int[] incrementArray(int[] a, int increment) { int[] temp = new int[a.length]; int i; for (i = 0; i < a.length; i++) temp[i] = a[i] + increment; return temp; }
In Java, a method may not return an array
a) 10 b) 0 c) 9
In the array double[] score = new double[10]; what is a) the value of score.length? b) the first index of score? c) the last index of score?
16. public static int max(int... arg) { if (arg.length == 0) { System.out.println( "Fatal Error: maximum of zero values."); System.exit(0); } int largest = Integer.MIN_VALUE; for (int element : arg) if (element > largest) largest = element; return largest; }
Rewrite the class GolfScores from Display 6.4 making the array of scores a static variable. Also, make the int variable numberUsed a static variable. Start with Display 6.4, not with the answer to Self-Test Exercise 14. Hint: All, or at least most, methods will have no parameters.
14. The only changes are to add the method differenceArray and to rewrite the method showDifference as follows (the complete class definition is in the file GolfScoresExercise.java on the accompanying website): public static void showDifference(double[] a, int numberUsed) { double average = computeAverage(a, numberUsed); System.out.println("Average of the " + numberUsed + " scores = " + average); double[] difference = differenceArray(a, numberUsed, average); System.out.println("The scores are:"); for (int index = 0; index < numberUsed; index++) System.out.println(a[index] + " differs from average by " + difference[index]); }
Rewrite the class GolfScores from Display 6.4 using the method differenceArray from Self-Test Exercise 13.
public void takeArray(int[] myArray) { for (int i = 0; i < myArray.length; i++) { // shows that the length can be extracted from the passed in array. // do stuff } }
Simple example of a method that takes in an int array as a parameter:
Which part will contain a compile error: enum StopLight {Red, Greed, Yellow}; StopLight myLight = StopLight.Red; StopLight myLight = StopLight.Blue;
StopLight myLight = StopLight.Blue;
Workday startDay = WorkDay.MONDAY;
Syntax to refer to a emum variable enumm Workday {MONDAY, TUESDAY,WEDNESDAY,THURSDAY, FRIDAY);
Syntax of System.arraycopy method.
System.arraycopy(from, fromStart, to, toStart, count);
True
T o F A method with an array parameter must specify the base type of the array only BaseType[]
True
T or F An array can have indexed variables of any type, including any class type.
False
T or F An array index cannot be computed when a program is run It may not be represented by an expression that evaluates to a suitable integer: score[next + 1]
True Accessor methods that return a variety of information about the array and its elements may be sufficient
T or F When an instance variable names an array, it is not always necessary to provide an accessor method that returns the contents of the entire array.
indexed
The _____________ variables of an array can be used as an argument to be plugged in for a parameter of the array's base type.
indexed
The _____________ variables of an array can be used just like any other variables of the base type of the array.
a, b, c,
What is the output of the following code? char[] letter = {'a', 'b', 'c'}; for (int index = 0; index < letter.length; index++) System.out.print(letter[index] + ", ");
1 2 3 4 5
What is the output?
16
What is the output?
3.0 4.5 1.0 2.5 5.0 3.0 2.0 3.0
What is the output?
4.5 5.0
What is the output?
42.0
What is the output?
5
What is the output?
6
What is the output?
The method will compile and run. The array returned has the correct values for its elements. However, the method will change the values of its array argument. If you want to change the values in the array argument, a void method would make more sense. If you want to return an array, you should probably return a new array (as in the version in the previous subsection), not return a changed version of the argument array.
What is wrong with the following method definition? It is an alternate definition of the method by the same name defined in the previous subsection. It will compile. public static char[] upperCaseVersion(char[] a) { char i; for (i = 0; i < a.length; i++) a[i] = Character.toUpperCase(a[i]); return a; }
The for loop uses indices 1 through sampleArray.length, but the correct indices are 0 through sampleArray.length - 1. The last index, sampleArray.length, is out of bounds. What was probably intended is the following: int[] sampleArray = new int[10]; for (int index = 0; index < sampleArray.length; index++) sampleArray[index] = 3*index;
What is wrong with the following piece of code? int[] sampleArray = new int[10]; for (int index = 1; index <= sampleArray.length; index++) sampleArray[index] = 3*index;
partially filled
When using a _______________ array, your program needs an additional variable of type int to keep track of how much of the array is being used.
Yes
Would this cause a privacy leak? public double[] getArray() { double[] temp = new double[count]; for (int i = 0; i < count; i++) temp[i] = a[i]; return temp }
Yes
Would this produce an out of bounds error?
public static void oneMore(int[] a) { for (int i = 0; i < a.length; i++) a[i] = a[i] + 1; }
Write a method definition for a static void method called oneMore, which has a formal parameter for an array of integers and increases the value of each array element by one. (The definition will go in a class, but you need only give the method definition.)
public static int outOfOrder(double[] a) { for (int index = 0; index < a.length - 1; index++) if (a[index] > a[index + 1]) return (index + 1); return 1; }
Write a method named outOfOrder that takes as a parameter an array of double and returns a value of type int. This method will test the array for being out of order, meaning that the array violates the condition: a[0] <= a[1] <= a[2] <= ... The method returns -1 if the elements are not out of order; otherwise, it returns the index of the first element of the array that is out of order. For example, consider the following declaration: double[] a = {1.2, 2.1, 3.3, 2.5, 4.5, 7.9, 5.4, 8.7, 9.9, 1.0}; In the array above, a[2] and a[3] are the first pair out of order, and a[3] is the first element out of order, so the method returns 3. If the array is sorted, the method returns −1.
Syntax for array element access
arrayReference[index] Ex. data[2]
How do you access the last index of an array?
arrayReference[length - 1]
page.length is equal to 30 page[0].length is equal to 100
char[][] page = new char[30][100]; page.length is equal to ____ page[0].length is equal to _________
1.1 2.2 3.3 1.1 3.3 3.3
double[] a = {1.1, 2.2, 3.3}; System.out.println(a[0] + " " + a[1] + " " + a[2]); a[1] = a[2]; System.out.println(a[0] + " " + a[1] + " " + a[2]);
How to grow an array that has run out of space.
double[] newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;
Syntax of copying an array.
double[] prices = (double[]) data.clone();
Create an array of type double called score of length 5
double[] score = new double[5]; or double[] score; score = new double[5];
Syntax for creating an array with 3 rows and 3 columns.
final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String [ROWS][COLUMNS];
How to fill or search a 2D array.
for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";
A ________________ is a good way to step through the elements of an array and perform some program action on each indexed variable.
for loop