CopyArrayGood - printArray(prices); //change 3rd element in...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
//Program correctly copies data array into prices array using a deep copy / import java.util.Scanner; i public class CopyArrayGood { public static void main (String [] args) { double [] data = {1.25, 4.95, 5.00, .99, 10.23}; double [] prices = new double [data.length]; // double [] prices = data; DO NOT DO THIS //but rather copy element by element for (int i = 0; i < data.length; i++) { prices[i] = data[i]; } //OR use System.arraycopy // System.arraycopy(data, 0, prices, 0, data.length); System.out.println("original array is :"); printArray(data); System.out.println("copy array is :");
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: printArray(prices); //change 3rd element in prices array to 10.00 - this should not effect original array //but it does becasue the copy was a shallow copy - copied the references not the contents prices[2] = 10.00; System.out.println(&quot;original array is :&quot;); printArray(data); System.out.println(&quot;copy array is :&quot;); printArray(prices); } //Method to print contents of an array public static void printArray(double arr) { for(int i = 0; i &lt; arr.length; i++) { System.out.println(arr[i]); } } }...
View Full Document

Ask a homework question - tutors are online