introducing arrays. too many variables? remember, a variable is a data structure that can hold a...
DESCRIPTION
Introducing Arrays An array might prove a better solution to my problem! An array is a data structure that contains related items that are of the same data type and where each item in the array shares the same name. In memory, array values occupy contiguous locations.TRANSCRIPT
Introducing ArraysIntroducing Arrays
Too Many Variables?Too Many Variables?
Remember, a Remember, a variablevariable is a data structure is a data structure that can hold a that can hold a single valuesingle value at any given at any given time.time.
What if I want to create an application to What if I want to create an application to track student progress in a class with 50 track student progress in a class with 50 students? Creating 50 variables will prove students? Creating 50 variables will prove inefficient …inefficient …
Introducing ArraysIntroducing Arrays An An arrayarray might prove a better solution to my might prove a better solution to my
problem!problem! An An arrayarray is a data structure that contains related is a data structure that contains related
items that are of the same data type and where items that are of the same data type and where each item in the array shares the same name. each item in the array shares the same name.
In memory, array values occupy In memory, array values occupy contiguous contiguous locations.locations.
Multiple Variables in MemoryMultiple Variables in Memoryst
u1st
u1
stu2
stu2
stu3
stu3
stu4
stu4
stu5
stu5
stu6
stu6
stu7
stu7
stu8
stu8
stu9
stu9
stu1
0st
u10
stu1
1st
u11
stu1
2st
u12
String stu1, stu2, stu3, stu4, stu5, stu6, stu7, stu8, stu9, stu10, stu11, stu12;
Printing all the studentsPrinting all the studentsSystem.out.println( stu1 );System.out.println( stu1 );System.out.println( stu2 );System.out.println( stu2 );System.out.println( stu3 );System.out.println( stu3 );System.out.println( stu4 );System.out.println( stu4 );System.out.println( stu5 );System.out.println( stu5 );System.out.println( stu6 );System.out.println( stu6 );System.out.println( stu7 );System.out.println( stu7 );System.out.println( stu8 );System.out.println( stu8 );
System.out.println( stu9 );System.out.println( stu9 );System.out.println( stu10 );System.out.println( stu10 );System.out.println( stu11 );System.out.println( stu11 );System.out.println( stu12 );System.out.println( stu12 );
// How many lines if I wanted to print 200 students?// How many lines if I wanted to print 200 students?
An Array in MemoryAn Array in Memory
fopStufopStu
String[ ] fopStu = new String[12];fo
pStu
[0]
fopS
tu[0
]
fopS
tu[1
]fo
pStu
[1]
fopS
tu[2
]fo
pStu
[2]
fopS
tu[3
]fo
pStu
[3]
fopS
tu[4
]fo
pStu
[4]
fopS
tu[5
]fo
pStu
[5]
fopS
tu[6
]fo
pStu
[6]
fopS
tu[7
]fo
pStu
[7]
fopS
tu[8
]fo
pStu
[8]
fopS
tu[9
]fo
pStu
[9]
fopS
tu[1
0]fo
pStu
[10]
fopS
tu[1
1]fo
pStu
[11]
Reference to the Array
Array
Printing all the students in arrayPrinting all the students in arrayfor(int index = 0; index < 12; index++)for(int index = 0; index < 12; index++){{
System.out.println( stu[index] );System.out.println( stu[index] );}}
// How many lines if I wanted to print 200 students?// How many lines if I wanted to print 200 students?
Creating an Creating an EmptyEmpty Array in Two Array in Two StepsSteps
A previous slide showed the line of code:A previous slide showed the line of code:
String[ ] fopStu;
This line is an example of how to create a reference to an array of Strings. This does not create the array object.
To create the array we need the following line of code:
fopStu = new String[12];
This line is an example of how to create an Array of Strings references. THERE ARE NO STRINGS. Just 12 adjacent memory locations waiting to point at Strings
Creating an Creating an EmptyEmpty Array in a Array in a Single StepSingle Step
In general, to create an array of any type, you use the following:
Create a reference assign it an Array object.
<datatype> [ ] <arrayName> = new <datatype> [ <number of cells> ];
Therefore, if you wanted to create an Array to hold 15 Robots, you would type the following:
Robot[ ] myRobots = new Robot[15];
This will create a reference to a Robot array that CAN hold 15 individual robots. After this code, NO ACTUAL Robots exist. There are just 15 Robot references in side of the Array.
Creating an Creating an EmptyEmpty Array in Two Array in Two StepsSteps
In some cases you may want to create the array reference, separately In some cases you may want to create the array reference, separately from the actual array. You can break the statement into two parts.from the actual array. You can break the statement into two parts.
Robot[ ] myRobots = new Robot[15];
would become:
Robot[ ] myRobots;
myRobots = new Robot[15]; //myRobots refers to an array that can hold 15 Robots
Since arrays are object, the reference could later be used to “point” to a new array. In other words, the reference could be reassigned.
myRobots = new Robot[25]; //myRobots now refers to an new array that can hold 25 // Robots the old Array and all its contents are now gone
Assigning Values to an ArrayAssigning Values to an Array To assign a value to an array (after it has been created), To assign a value to an array (after it has been created),
you need to call the array by its name and then provide a you need to call the array by its name and then provide a subscriptsubscript to store the new value (the index number to store the new value (the index number goes in a pair of square brackets):goes in a pair of square brackets):
String [] fopStu = new String [12];String [] fopStu = new String [12];fopStu[4] = "Jacob";fopStu[4] = "Jacob";fopStu[5] = “Sally”;fopStu[5] = “Sally”;
Robot [] myRobots = new Robot[4];Robot [] myRobots = new Robot[4];myRobots[3] = new Robot(1,1,North,0);myRobots[3] = new Robot(1,1,North,0);
The The array length array length fieldfield Once an array is created, its size is fixed. It cannot Once an array is created, its size is fixed. It cannot
be changed. The argument in the [be changed. The argument in the [lengthlength] fixes ] fixes the size of the array when it is created.the size of the array when it is created.
We can find how many elements an array has by We can find how many elements an array has by accessing the accessing the lengthlength field. field.
You can find its size of an arrayYou can find its size of an arrayint numStu = fopStu.length;int numStu = fopStu.length;
lengthlength is always a nonnegative integer value: is always a nonnegative integer value:Based on previous slides, this would assign the value Based on previous slides, this would assign the value
12 into the variable numStu12 into the variable numStu. .
An Array in Memory(again)An Array in Memory(again)
fopStufopStu
String[ ] fopStu = new String[12];
fopS
tu[0
]fo
pStu
[0]
fopS
tu[1
]fo
pStu
[1]
fopS
tu[2
]fo
pStu
[2]
fopS
tu[3
]fo
pStu
[3]
fopS
tu[4
]fo
pStu
[4]
fopS
tu[5
]fo
pStu
[5]
fopS
tu[6
]fo
pStu
[6]
fopS
tu[7
]fo
pStu
[7]
fopS
tu[8
]fo
pStu
[8]
fopS
tu[9
]fo
pStu
[9]
fopS
tu[1
0]fo
pStu
[10]
fopS
tu[1
1]fo
pStu
[11]
Note that each “cell” of the array has a separate index value. The smallest index value will ALWAYS be 0, and the largest will ALWAYS be one less than the length of the array. If the length is 12, then the max index is 11.
Initializing ArraysInitializing Arraysint[] myList = new int[5];int[] myList = new int[5];
for (int i = 0; i < myList.length; i++)for (int i = 0; i < myList.length; i++) myList[i] = i * i;myList[i] = i * i;
Would create the following array:Would create the following array:
myList 00 11 44 99 1616
myList[0] myList[1] myList[2] myList[3] myList[4]
Initializing ArraysInitializing ArraysRobot[] myBots = new Robot[3];Robot[] myBots = new Robot[3];
for (int i = 0; i < myBots.length; i++)for (int i = 0; i < myBots.length; i++) myBots[i] = new Robot(1,i+1,North,0);myBots[i] = new Robot(1,i+1,North,0);
Would create the following array:Would create the following array:
myBots
myBots[0] myBots[1] myBots[2]
Robot @ (1,1)
Facing North
0 Beepers
Robot @ (1,2)
Facing North
0 Beepers
Robot @ (1,3)
Facing North
0 Beepers
Array Elements & SubscriptsArray Elements & Subscripts An An elementelement is an object referenced in an array. Java is an object referenced in an array. Java
stores each element in a different position in an array. stores each element in a different position in an array. We reference a position using a We reference a position using a subscriptsubscript (a.k.a. (a.k.a. indexindex). ). To reference an element, we need to provide the array's To reference an element, we need to provide the array's
name and the element's subscript:name and the element's subscript:
myBots[0].move();myBots[0].move(); Each element in a array behaves exactly like a reference Each element in a array behaves exactly like a reference
of the same type.of the same type.
Creating an Array with Initial ValuesCreating an Array with Initial Values
When we are declaring an array, we can When we are declaring an array, we can supply specific values in a comma-delimited supply specific values in a comma-delimited list:list:
String[ ] students = {"James","Ravi","Mary”,”Jackson“};String[ ] students = {"James","Ravi","Mary”,”Jackson“};
int[ ] stuIds = { 8752, 9062, 6087, 8745, 2354, 1298}; int[ ] stuIds = { 8752, 9062, 6087, 8745, 2354, 1298};
Robot [] robs = { new Robot(1, 1, North, 3),Robot [] robs = { new Robot(1, 1, North, 3), new Robot(1, 2, North, 3),new Robot(1, 2, North, 3), new Robot(1, 3, North, 3),new Robot(1, 3, North, 3), new Robot(1, 4, North, 3)};new Robot(1, 4, North, 3)};
Creating an Array with Initial Values Creating an Array with Initial Values (con’t)(con’t)
double[] myList = {1.9, 2.9, 3.4, 3.5};double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the This shorthand notation is equivalent to the following statements:following statements:double[] myList = new double[4];double[] myList = new double[4];
myList[0] = 1.9;myList[0] = 1.9;
myList[1] = 2.9;myList[1] = 2.9;
myList[2] = 3.4;myList[2] = 3.4;
myList[3] = 3.5; myList[3] = 3.5;
CAUTIONCAUTIONUsing the shorthand notation, Using the shorthand notation, you have to declare, create, and you have to declare, create, and initialize the array all in one initialize the array all in one statement. Splitting it would statement. Splitting it would cause a syntax error. cause a syntax error. For For example, the following is wrong:example, the following is wrong:double[] myList;double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};myList = {1.9, 2.9, 3.4, 3.5};
Accessing Array ValuesAccessing Array Values To access a value from an array, call the To access a value from an array, call the
array by name and indicate which array by name and indicate which subscript you want to retrieve (the index subscript you want to retrieve (the index number goes in a pair of square brackets): number goes in a pair of square brackets):
String name = fopStu[3];String name = fopStu[3];int id = stuIds[3];int id = stuIds[3];Robot karel = myBots[2];Robot karel = myBots[2];
Copying ArraysCopying ArraysA simple assignment cannot copy arrays. Since an array is an object, if A simple assignment cannot copy arrays. Since an array is an object, if you try to use the assignment operator (=) you will end up with two you try to use the assignment operator (=) you will end up with two references to the same array. If myList is the following array:references to the same array. If myList is the following array:
myList 00 11 44 99 1616myList[0] myList[1] myList[2] myList[3] myList[4]
then,then,int[] anotherName;int[] anotherName;anotherName = myList;anotherName = myList;
will result in:will result in:
myList00 11 44 99 1616
myList[0] myList[1] myList[2] myList[3] myList[4]
anotherName anotherName[0] anotherName[1] anotherName[2] anotherName[3] anotherName[4]
The statement: The statement: anotherName[3] = 5;anotherName[3] = 5; would also effect myList[3] would also effect myList[3]
Traversing ArraysTraversing Arrays To traverse an array means to “visit” each cell in order, doing To traverse an array means to “visit” each cell in order, doing
whatever the job may be.whatever the job may be. forfor loops do a VERY good job of this.loops do a VERY good job of this.
BeeperSweeper [] sweepers = new BeeperSweeper[9];BeeperSweeper [] sweepers = new BeeperSweeper[9];. . .. . .// code to initialize all 9 cells with sweeper in // code to initialize all 9 cells with sweeper in // appropriate locations// appropriate locations. . .. . .for(int i = 0; i < sweepers.length; i++)for(int i = 0; i < sweepers.length; i++)sweepers[i].task();sweepers[i].task();
This code will invoke each sweepers task method, without having to name 9 This code will invoke each sweepers task method, without having to name 9 different robots and use 9 lines of code to invoke the task methods.different robots and use 9 lines of code to invoke the task methods.
Would the Would the forfor loop still work if the array were created and initialized with a loop still work if the array were created and initialized with a different number of BeeperSweepers?different number of BeeperSweepers?
Sample AlgorithmsSample Algorithms
Summing/accumulatingSumming/accumulating Finding largestFinding largest Finding smallestFinding smallest SearchingSearching Sorting by ….Sorting by ….
SummarySummary Arrays are data structures that can hold Arrays are data structures that can hold
multiple values at the same time.multiple values at the same time. The values in an array are called elements The values in an array are called elements
and they share the same name (the and they share the same name (the array's name), but are accessed through array's name), but are accessed through unique subscripts (indicies).unique subscripts (indicies).
continued …continued …
SummarySummary Subscript (index) numbering always Subscript (index) numbering always
begins with zero and goes up to the length begins with zero and goes up to the length of the array-1. of the array-1.
The size of an array can be found by using The size of an array can be found by using the the lengthlength field. field.
When arrays are created, they are initially When arrays are created, they are initially empty. If you want them to hold empty. If you want them to hold something, YOU must put it in.something, YOU must put it in.
continued …continued …
SummarySummary
forfor loops are very useful in traversing an loops are very useful in traversing an array.array.
Arrays are object, and therefore cannot be Arrays are object, and therefore cannot be duplicated with the assignment (=) duplicated with the assignment (=) operator.operator.
Assignment Part 2Assignment Part 2**
From the From the CarDealerCarDealer Project, complete the Project, complete the DealerDealer class. class.
You will need to implement the following:You will need to implement the following:• public boolean find(Car c)public boolean find(Car c)• public double getInventoryValue()public double getInventoryValue()• public double getAverageCarValue()public double getAverageCarValue()• public Car getMostValuableCar()public Car getMostValuableCar()• public Car getLeastValuableCar()public Car getLeastValuableCar()• public void sortCarsByYear()public void sortCarsByYear()• public void sortCarsByValue()public void sortCarsByValue()
*See the IntroObjects PowerPoint for Asignment Part 1*See the IntroObjects PowerPoint for Asignment Part 1Help for the above methods can be found in the ArrayAlgorithms PowerPointHelp for the above methods can be found in the ArrayAlgorithms PowerPoint