Date post: | 12-Jan-2016 |
Category: |
Documents |
Upload: | bertram-taylor |
View: | 313 times |
Download: | 6 times |
Chapter 7 Arrays and Vectors Introducing ArraysIntroducing Arrays Declaring Arrays, Creating Arrays, and Declaring Arrays, Creating Arrays, and
Initializing ArraysInitializing Arrays Array of ObjectsArray of Objects Copying ArraysCopying Arrays Multidimensional ArraysMultidimensional Arrays Numeric Wrapper ClassesNumeric Wrapper Classes Command-Line ParametersCommand-Line Parameters Creating Generic ClassesCreating Generic Classes The Vector ClassThe Vector Class
Introducing Arrays
double[] myList = new double[10]
Array is a data structure that represents a collection of the same types of data. Java treats these arrays as objects.
An Array of 10 Elementsof type double
Declaring Arrays datatype[] arrayname;datatype[] arrayname;
Example:Example:int[] myList;int[] myList;
datatype arrayname[];datatype arrayname[];
Example:Example:int myList[];int myList[];
Creating Arrays
arrayName = new datatype[arraySize];arrayName = new datatype[arraySize];
Example:Example:
myList = new double[10];myList = new double[10];
Declaring and Creatingin One Step datatype[] arrayname = newdatatype[] arrayname = new
datatype[arraySize];datatype[arraySize];
double[] myList = new double[10];double[] myList = new double[10];
datatype arrayname[] = newdatatype arrayname[] = new datatype[arraySize]; datatype[arraySize];
double myList[] = new double[10];double myList[] = new double[10];
Initializing Arrays
Using a loop:Using a loop:
for (int i = 0; i < myList.length; i++)for (int i = 0; i < myList.length; i++)
myList[i] = (double)i;myList[i] = (double)i;
Declaring, creating, initializing in one Declaring, creating, initializing in one step:step:
double[] myList = {1.9, 2.9, 3.4, 3.5};double[] myList = {1.9, 2.9, 3.4, 3.5};
Example 7.1Assigning Grades Objective: Objective: read student scores (read student scores (intint) from the ) from the
keyboard, get the best score, and then assign keyboard, get the best score, and then assign grades based on the following scheme:grades based on the following scheme: Grade is A if score is >= best–10;Grade is A if score is >= best–10; Grade is B if score is >= best–20;Grade is B if score is >= best–20; Grade is C if score is >= best–30;Grade is C if score is >= best–30; Grade is D if score is >= best–40;Grade is D if score is >= best–40; Grade is F otherwise.Grade is F otherwise.
AssignGradeAssignGrade
RunRun
Example 7.2Using Arrays in Sorting
Objective: Use the Objective: Use the selectionSortselectionSort method to method to write a program that will sort a list of write a program that will sort a list of double floating-point numbers. double floating-point numbers.
SelectionSortSelectionSort RunRun
Example 7.3Testing Linear Search
Objective: Implement and test the linear Objective: Implement and test the linear search method by creating an array of 10 search method by creating an array of 10 elements of elements of intint type randomly and then type randomly and then displaying this array. Prompt the user to displaying this array. Prompt the user to enter a key for testing the linear search. enter a key for testing the linear search.
LinearSearchLinearSearch RunRun
Array of Objects Declaring and creating:Declaring and creating:
Circle[] circleArray = new Circle[10];Circle[] circleArray = new Circle[10];
Initializing:Initializing:
for (int i=0; i<circleArray.length; i++)for (int i=0; i<circleArray.length; i++){ {
circleArray[i] = new Circle();circleArray[i] = new Circle();}}
Example 7.5Summarizing the Areas of Circles
Objective: Objective: Summarize the areas of an Summarize the areas of an array of circlesarray of circles
TotalAreaTotalArea RunRun
Copying Arrays
Using a loop:Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArrays.length; i++)for (int i = 0; i < sourceArrays.length; i++)
targetArray[i] = sourceArray[i];targetArray[i] = sourceArray[i];
The arraycopy Utility
arraycopy(sourceArray, src_pos, targetArray, arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);tar_pos, length);
Example:Example:System.arraycopy(sourceArray, 0, targetArray, 0, System.arraycopy(sourceArray, 0, targetArray, 0,
sourceArray.length);sourceArray.length);
Multidimensional Arrays
int[][] matrix = new int[10][10];int[][] matrix = new int[10][10];
ororint matrix[][] = new int[10][10];int matrix[][] = new int[10][10];
for (int i=0; i<matrix.length; i++)for (int i=0; i<matrix.length; i++) for (int j=0; j<matrix[i].length; j++) { for (int j=0; j<matrix[i].length; j++) { matrix[i][j] = (int)(Math.random()*1000);matrix[i][j] = (int)(Math.random()*1000);
}}
Example 7.7Adding and Multiplying Two Matrices
Objective: Use two-dimensional arrays to Objective: Use two-dimensional arrays to create two matrices, and then add and create two matrices, and then add and multiple the two matrices.multiple the two matrices.
TestMatrixOperationTestMatrixOperation RunRun
55555454535352525151
45454444434342424141
35353434333332323131
25252424232322222121
15151412131212121111
5554535251
4544434241
3534333231
2524232221
1514131211
5554535251
4544434241
3534333231
2524232221
1514131211
bababababa
bababababa
bababababa
bababababa
bababababa
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
Numeric Wrapper Classes
BooleanBoolean
CharacterCharacter
ShortShort
ByteByteObject
-
Double-
Float-
Long-
Integer-
Short-
Byte-
Character-
Boolean-
Number-
Long
Float
Double
The Integer Classand The Double Class ConstructorsConstructors
Class Constants Class Constants MAX_VALUEMAX_VALUE, , MIN_VALUEMIN_VALUE
Conversion MethodsConversion Methods
Command-Line Parameters
class TestMainclass TestMain
{{
public static void main(String[] args)public static void main(String[] args)
{ ... }{ ... }
}}
java TestMain arg0, arg1, arg2, ..., argnjava TestMain arg0, arg1, arg2, ..., argn
ProcessingCommand-Line Parameters
In the main method, get the arguments from In the main method, get the arguments from args[0], args[1], ..., args[n]args[0], args[1], ..., args[n], which corresponds , which corresponds to to arg0, arg1, ..., argnarg0, arg1, ..., argn in the command line. in the command line.
Example 7.8Using Command-Line Parameters
Objective: Write a program that will Objective: Write a program that will perform binary operations on integers. perform binary operations on integers. The program receives three parameters: The program receives three parameters: an operator and two integers.an operator and two integers.
CalculatorCalculatorRunRun java Calculator + 2 3
RunRun java Calculator - 2 3
RunRun java Calculator / 2 3
Example 7.9Designing Generic Classes
Objective: This example gives a generic class Objective: This example gives a generic class for matrix arithmetic. This class implements for matrix arithmetic. This class implements matrix addition and multiplication common for matrix addition and multiplication common for all types of matrices.all types of matrices.
GenericMatrixGenericMatrix
Example 7.10Extending Abstract Classes
GenericMatrix
-Object[][] matrix
#GenericMatrix(Object[][] matrix)
+Object[][] getMatrix() +void setMatrix(Object[][] matrix) +Object[][] addMatrix(Object[][] secondMatrix) +Object[][] multiplyMatrix(Object[][] secondMatrix) +void printResult( GenericMatrix m1, GenericMatrix m2, GenericMatrix m3, char op) #GenericMatrix createGenericMatrix() #Object add(Object o1, Object o2) #Object multiply(Object o1, Object o2) #Object zero()
IntegerMatrix
RationalMatrix
Example 7.10Extending Abstract Classes, cont.
Objective: This example gives two programs Objective: This example gives two programs that utilize the GenericMatrix class for integer that utilize the GenericMatrix class for integer matrix arithmetic and rational matrix matrix arithmetic and rational matrix arithmetic.arithmetic.
TestIntegerMatrixTestIntegerMatrix RunRun
TestRationalMatrixTestRationalMatrix RunRunRationalMatrixRationalMatrix
IntegerMatrixIntegerMatrix
The Vector Class
Java provides the Vector class in the java.util Java provides the Vector class in the java.util package, which can be used to store an package, which can be used to store an unspecified number of elements. A vector can unspecified number of elements. A vector can grow or shrink dynamically as needed. grow or shrink dynamically as needed.
The Vector Class, cont.
To create a vector, you can use its default To create a vector, you can use its default constructor like this:constructor like this:Vector vector = new Vector();Vector vector = new Vector();
To add an element to the vector, use the To add an element to the vector, use the addElement method as follows:addElement method as follows:
vector.addElement(anObject); vector.addElement(anObject);
The element in the vector must be an object.The element in the vector must be an object.
The element is appended to the vector.The element is appended to the vector.
The Vector Class, cont.
To retrieve an element, use the elementAt To retrieve an element, use the elementAt method as follows:method as follows:
Object anObject = vector.elementAt(0);Object anObject = vector.elementAt(0);
To find the number of elements in the vector, To find the number of elements in the vector, use the size method as follows:use the size method as follows:
int numOfElements = vector.size();int numOfElements = vector.size();
Example 7.10 Assigning Grades Using a Vector
Objective: Objective: Rewrites Example 7.1 using a Rewrites Example 7.1 using a vector, instead of using an array. The vector, instead of using an array. The program reads student scores from the program reads student scores from the keyboard, stores the score in the vector, keyboard, stores the score in the vector, finds the best score, and then assigns finds the best score, and then assigns grades for all the students. grades for all the students.
AssignGradeUsingVectorAssignGradeUsingVector RunRun