MIS 222 – Lecture 12 10/9/2003
Assignment 11 Demo 8.1.10
Arrays Company Profits 1 4000 2 122154 3 55255 4 -564654 5 541818 6 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; Company Profits 1 4000 2 122154 3 55255 4 -564654 5 541818 6 781849 7 -121518 8 843257 Exact same data types Similar information
Array Literals 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 Example 8.2.1
Shallow Copy 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 1 2 3 4 5 6 7 4000 122154 55255 -564654 541818 781849 -121518 843257 8475
Deep Copy 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 1 2 3 4 5 6 7 4000 122154 55255 -564654 541818 781849 -121518 843257 8475 myComps 9985 1 2 3 4 5 6 7 4000 122154 55255 -564654 541818 781849 -121518 843257 9985
Arrays as Arguments (to methods) Average() int[] int 8475 companies 4000 122154 55255 -564654 541818 781849 -121518 843257 1 2 3 4 5 6 7 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 1 2 3 8475 5 15.5 55.55 1 8475
Example 8.3.7