120 likes | 358 Views
MIS 222 – Lecture 12. 10/9/2003. Assignment 11. Demo 8.1.10. Arrays. int[] companies = new int[8]; companies[0] = 4000; companies[1] = 122154; companies[2] = 55255; companies[3] = -564654; companies[4] = 541818; companies[5] = 781849; companies[6] = 121518; companies[7] = 121518;.
E N D
MIS 222 – Lecture 12 10/9/2003
Assignment 11 • Demo • 8.1.10
Arrays int[] companies = new int[8]; companies[0] = 4000; companies[1] = 122154; companies[2] = 55255; companies[3] = -564654; companies[4] = 541818; companies[5] = 781849; companies[6] = 121518; companies[7] = 121518; • Exact same data types • Similar information
int[] companies = {4000, 122154, 55255, -564654, 541818, 781849, 121518, 121518}; enclosed in brackets separated by commas String[] letters = {“a”, “b”, “c”}; System.out.println(letters[2]); System.out.println(letters[3]); Array Literals
Array Literals Example • 8.2.1
Array Copying int[] companies = {4000, 122154, 55255, -564654, 541818, 781849, 121518, 121518}; int[] myComps = companies; myComps[0] = 1; System.out.println(companies[0]); companies 8475 Shallow Copy myComps 8475 0 1 2 3 4 5 6 7 4000 122154 55255 -564654 541818 781849 -121518 843257 8475
Array Copying int[] companies = {4000, 122154, 55255, -564654, 541818, 781849, 121518, 121518}; int[] myComps =new int[companies.length]; System.arraycopy(companies, 0, myComps, 0, companies.length); myComps[0] = 1; System.out.println(companies[0]); companies 8475 Deep Copy 0 1 2 3 4 5 6 7 4000 122154 55255 -564654 541818 781849 -121518 843257 8475 myComps 9985 0 1 2 3 4 5 6 7 4000 122154 55255 -564654 541818 781849 -121518 843257 9985
companies 8475 0 1 2 3 4 5 6 7 4000 122154 55255 -564654 541818 781849 -121518 843257 8475 Arrays as Arguments (to methods) Average() int[] int 25
Arrays as Arguments Here’s what it looks like: public class Average { public static void main(String[] args){ double[] stuff = {5,15.5,55.55,1}; double avg = average(stuff); System.out.println(“average of stuff is “ + avg); } public static double average(double[] nums){ double total = 0; for(int i = 0; i < nums.length; i++){ total += nums[i]; } return total / num.length; } }
Arrays as Arguments public class Average { public static void main(String[] args){ double[] stuff = {5,15.5,55.55,1}; double avg = average(stuff); System.out.println(“the third element is “ + stuff[2]); } public static double average(double[] nums){ double total = 0; for(int i = 0; i < nums.length; i++){ total += nums[i]; } //malicious code nums[2] = -999999999; return total / num.length; } }
Arrays as Arguments public class Average { public static void main(String[] args){ double[] stuff = {5,15.5,55.55,1}; double avg = average(stuff); System.out.println(“the third element is “ + stuff[2]); } public static double average(double[] nums){ //body same as previous slide } } stuff 8475 nums 0 1 2 3 8475 5 15.5 55.55 1 8475
Example • 8.3.7