9 2D Arrays One
9 2D Arrays One
Reading: Chapter 9
• Example:
• Creating an array requires two steps (for both 1-D and 2-D arrays):
1. Declaring the reference to the array
2. Instantiating the array.
• To instantiate an array:
arrayName = new datatype[ rowSize ] [ colSize ];
• rowSize is an int and is the number • colSize is an int and is the number
of rows that will be in the array. of columns that will be in the array.
• Examples:
• When an array is instantiated, the elements are assigned default values as follows:
boolean false
• The declaration of an array creates an area of memory that holds the elements of the array.
• This area of memory has one name, the name of the array.
double [][] zapNums = new double [3][5];
zapNums
0.0 0.0 0.0 0.0 0.0
zapNums[0][2] = 7.5;
zapNums
0.0 0.0 0.0
-6.2
7.5 0.0 0.0 zapNums[1][0] = 42.0;
0.0
42.0 0.0 0.0 0.0 0.0
99.0
zapNums[1][4] = 99.0;
0.0 0.0 0.0 0.0
87.5 0.0
zapNums[2][3] = 87.5;
zapNums[0][2] = -6.2;
• Loops are the best way to print the contents of any array.
• Example:
zapNums
0.0 0.0 -6.2 0.0 0.0
for (int row = 0; row < 3; row++ ) { 0.0 0.0 -6.2 0.0 0.0
for (int col = 0; col < 5; col++ ) 42.0 0.0 0.0 0.0 99.0
System.out.println();
}
• It is best to have code that automatically knows how many rows and columns are present.
• For 2-D arrays, we need both the number of rows and the number of columns!
• For the number of columns, first specify which row, then ask for the length: arrayName[2].length
zapNums
0.0 0.0 -6.2 0.0 0.0
• Example:
• A comma separates rows.
double [][] grades = { { 91.0, 92, 93, 99.0, 85.5 },
{ 87.5, 100, 92.5, 75.0, 62.0 }, • No comma after last row.
{ 90, 69, 73, 82.5, 90.5 } };
Neatness counts!
Line things up when you enter the values.
• Outer set of { }’s define the
beginning and the end of the
array’s values.
• Want to compute the average for each row. For a grade book, the average is usually stored as the last column:
double [][] grades = { { 91.0, 92, 93, 99.0, 85.5, 0 },
{ 87.5, 100, 92.5, 75.0, 62.0, 0 },
{ 90, 69, 73, 82.5, 90.5, 0 } };
System.out.println();
}
• The inner loop computes the sum of the grades for one row:
for ( col = 0; col < grades[row].length - 1; col++)
• grades[row].length - 1
System.out.println();
}
System.out.println();
}
• Another way to initialize an array: Have the user type in the values.
System.out.println();
}
• The inner loop computes the sum of the grades for one column:
for ( row = 0; row < grades.length; row++)
System.out.println("The grades:");
System.out.println();
}
System.out.println(sum / grades.length);
}
grades
91 92 93 85.5
90 69 73 82.5 90.5
System.out.println();
}
System.out.println();
}
System.out.println();
• Write a method that returns a String containing the third name of each President:
public String thirdNames() {
String result = new String("");
int row;
for (row = 0; row < ______________________________; row++)
if ( ______________________________________________ )
result = result + presidents[row][2] + "\n";
return result;
}
• Write a method that takes an int argument that specifies which name is wanted:
public String names(int position) {
String result = new String("");
int row;
for (row = 0; row < ______________________________; row++)
if ( ___________________________________________ )
• What happens if position has a value larger than any of the names in the array?
// Check the rest of the rows for a row with more columns
for ( row = 1; row < grades.length; row++ )
if ( ___________________________________________________ )
mostColumns = grades[row].length;
// Check the rest of the rows for a row with more columns
for ( row = 1; row < grades.length; row++ )
if ( mostColumns < grades[row].length )
mostColumns = grades[row].length;
• Syntax:
accessSpecifier static dataType variableName;
• Examples:
public static int countAutos = 0;
private static short processID = 2;
• Allows use of Math.min(), Math.abs(), etc., without first having to create an instance of Math.
• The function main is declared static so it can be called by the Java Virtual Machine without creating an
instance of the class that contains main.
double x = Math.sqrt(1274.873);
static Non-static
Method Method
• An example that maintains a class variable and provides a wrap-around increment method.
public class ProcessID public ProcessID(){
{ // Get id for this object:
private static short pid = 2; myId = nextPid();
// Instance variables here... // rest of constructor here...
private short myId; } // end of constructor
• A Sequential Search can be used to determine if a specific value (the search key) is in an array.
• Approach:
• Start with the first element and compare each element to the search key:
• If found, return the index of the element that contains the search key.
• Example: A class that stores random integers in an array. Want to ask if a particular number is present in the
array.
return temp;
} // end of method toString
} // end of class Search1
System.out.println("first contains:");
System.out.println(first.toString());
System.out.println("second contains:");
System.out.println(second.toString());
System.out.println();
System.out.println("Searching in second:");
for ( i = -3; i < 7; i++ ) {
result = second.findNumber(i);
if ( result != -1 )
System.out.println(i + " found at position " + result);
else
System.out.println("Did not find " + i);
}
• If the search key is not in the array, we can detect that condition when we find a value that is higher than the
search key.
• All elements past that position will also be greater than the search key.
return -1;
} // end of method findNumber
return -1;
} // end of method findNumber
• For &&, when the first expression (on the left) is false, the second expression (on the right) is not
evaluated.
• For ||, when the first expression is true, the second expression is not evaluated.
• To guess a number between 1 and 100, start with 50 (the halfway point):
• If the answer is that the number is greater than our guess, we know to guess in the upper-half.
• If the answer is that the number is less than our guess, we know to guess in the lower-half.
• Keep guessing that the number is in the middle of the remaining numbers:
• How many guesses does it take (at most) to find a number between 1 and 100?
• This approach works because the values 1-100 are a “sorted” list of numbers.
• The Algorithm:
• Compare the middle element of the array with the search key.
• The Algorithm:
• Compare the middle element of the array with the search key.
• If they are equal, we found the search key. Return the index of this middle element.
• If the middle element’s value is > the search key, continue search in the left (lower) half of the array.
• If the middle element’s value is < the search key, continue search in the right (upper) half of the array.
• First step:
start middle end
0 3 6
0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62
• Second step:
start middle end
0 1 2
0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62
• Third step:
0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62
0 1 2 3 4 5 6 0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62 numbers -42 -12 -4 19 21 53 62
0 1 2 3 4 5 6 0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62 numbers -42 -12 -4 19 21 53 62
start > end; value not in the array
• Consider an somewhat larger array of 15 elements. Assume the search key is 81.
• First step:
start middle end
0 7 14
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98
• Second step:
start middle end
8 11 14
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98
• Consider an somewhat larger array of 15 elements. Assume the search key is 81.
• Third step:
start middle end
8 9 10
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98
• Fourth step:
start middle end
9 9 9
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98
• Consider an somewhat larger array of 15 elements. Assume the search key is 81.
• Fifth step:
start middle end
10 9 9
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98
• Etc.
• Those elements on the left that are not (yet) in order — the unsorted sub-array.
• Those elements on the right that are in order — the sorted sub-array.
maxLocation 6
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 97 62 73 89 65 98 21 19 -42 83 82 53 -4 -12
• Result after the swap of the numbers in location 6 and the last element in the array:
maxLocation 6
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 97 62 73 89 65 -12 21 19 -42 83 82 53 -4 98
unsorted sorted
• Find the location of the largest number in the unsorted portion of the array:
maxLocation 1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 97 62 73 89 65 -12 21 19 -42 83 82 53 -4 98
unsorted sorted
• Result after the swap of the numbers in location 1 and the next-to-last element in the array:
maxLocation 1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 -4 62 73 89 65 -12 21 19 -42 83 82 53 97 98
unsorted sorted
• Find the location of the largest number in the unsorted portion of the array:
maxLocation 4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 -4 62 73 89 65 -12 21 19 -42 83 82 53 97 98
unsorted sorted
• Result after the swap of the numbers in location 4 and the last element in the unsorted array:
maxLocation 4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 -4 62 73 53 65 -12 21 19 -42 83 82 89 97 98
unsorted sorted
• Find the index of the largest element. (We’ve done this before!)
private static int indexOfLargestElement( int [] values, int size )
{
int index = 0;
return index;
} // end of method indexOfLargestElement
• The “unsorted portion” of the array will be those elements in positions 0 to size.
• Declare a “temporary variable” of the same type as the elements of the array.
return index;
} // end of method indexOfLargestElement
} // end of Sorter
Sorter.selectionSort( numbers );
• Need a way to know the start and end times of the sort.
• Create an instance of Date. It will record the time at which it was created.
• Returns a long that contains the time at which the Date instance was created.
0
50,000 200,000 350000 500000
• Example: Want to keep track of sales on a per-year, per-week, and a per-day basis.
• First dimension: year What is the last day of the last year?
• Second dimension: week sales[9][51][6]
• Third dimension: day of the week What is the first day of 4th week of the last year?
• Sample code:
sales[9][3][0]
• Want the sales for one week all on the same line.
• Suppose we want the sales total for just the 4th year?
• What changes?
int year, week, day;
double sum = 0.0;
// for ( year = 0; year < sales.length; year++ )
year = 3;
for ( week = 0; week < sales[year].length; week++ )
for ( day = 0; day < sales[year][week].length; day++ ) {
sum = sum + sales[year][week][day];
}
• Suppose we want the sales total for all the sales in June (across all the years)?
• What changes?
int year, week, day;
double sum = 0.0;
for ( year = 0; year < sales.length; year++ )
for ( week = 21; week < 26; week++ )
for ( day = 0; day < sales[year][week].length; day++ ) {
sum = sum + sales[year][week][day];
}
• When it fills up, we create a larger array, and copy elements from the original to the larger array.
• All elements in an ArrayList are object references; i.e., String, Player, Chest, etc.
• That is, it is written to store object references of any type the client desires.
• Declaring an ArrayList:
ArrayList<String> aBunchOfNames;
• The type of object stored in the ArrayList is stated in between the < >'s
• The programmer can also state the desired number of initial items:
ArrayList<String> manyNames = new ArrayList<String>( 25 );
• Both start out with a size of 0, since no objects have been stored in either one.
add( E element)
boolean
appends element to the end of the list
clear( )
void
removes all the elements in the list
size( )
int
returns the number of elements in the list
remove( int index )
E
removes the element at the specified index position
get( int index )
E returns the element at the specified index position; the element is not removed
from the list
set( int index, E element )
E
replaces the element at the specified index position with the specified element
trimToSize( )
void
sets the capacity of the list to its current size