0% found this document useful (0 votes)
6 views

06Arrays

The document covers programming techniques related to arrays in Java, including their definition, types, and usage. It explains the differences between primitive and reference types, how to declare and create arrays, and how to manipulate them using loops and methods. Additionally, it discusses array equality, copying, cloning, and the concept of pass-by-value in method calls.

Uploaded by

Nhân Trọng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

06Arrays

The document covers programming techniques related to arrays in Java, including their definition, types, and usage. It explains the differences between primitive and reference types, how to declare and create arrays, and how to manipulate them using loops and methods. Additionally, it discusses array equality, copying, cloning, and the concept of pass-by-value in method calls.

Uploaded by

Nhân Trọng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

CompSci 230 S2 2017

Programming Techniques
Arrays
Agenda & Reading
 Topics:
 Introduction
 Primitive Types vs. Reference Types
 Arrays
 Multidimensional Arrays
 Arrays of Objects
 Reading
 Java how to program Late objects version (D & D)
 Chapter 6
 The Java Tutorial
 Arrays
 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
 http://www.tutorialspoint.com/java/java_arrays.htm
2 Lecture06
1.Introduction
 Data structures — collections of related data items.
 Array objects — data structures consisting of related data items of
the same type.
 Make it convenient to process related groups of values.
 Remain the same length once they’re created.
 Enhanced for statement : allows a program to access the data in
an array more easily than does the counter-controlled for
statement.
 Use variable-length argument lists to create methods that can
be called with varying numbers of arguments.
 Demonstrate how to process command-line arguments in
method main.
 static methods of class Arrays from the java.util package.
 ArrayLists are similar to arrays but provide additional
functionality,
3 Lecture06
2.Primitive Types vs. Reference Types
 Java is a strongly typed language.
 Java requires all variables to have a type.
 Java’s types are divided into primitive types and
reference types.
 Primitive types:
 boolean, byte, char, short, int, long, float and double.
 A variable of a primitive type is directly associated with a
int intA = 15;
memory location storing the value of the int variable.
intB = 10;

4 Lecture06
2.Primitive Types vs. Reference Types
 Reference Types:
 Any data type that is not a primitive type is a reference
type
 Programs use variables of reference types (normally called
references) to store the addresses of objects in the
computer’s memory.
 Such a variable is said to refer to an object in the program.
 If a variable is not initialized explicitly, the variable is given
the special value null.

Point b = new Point( 10, 20); b: Point


x =10
5 y =20 Lecture06
2.Primitive Types vs. Reference Types
 To call an object’s methods, you need a reference to
the object.
 If an object’s method requires additional data to perform
its task,
String then
s1 = you’d pass arguments in the method call.
new String("candide");
String s2 = s1.replace('d', 'p');

 Primitive-type variables do not refer to objects, so


such variables cannot be used to invoke methods.

6 Lecture06
int[] ages = new int[10];
String[] names = new String[10];

3.Arrays
 An array is a group of variables (called elements)
containing values that all have the same type.
 The type of an array is determined by its element
type, which is specified when the array is instantiated.
 Arrays are objects and thus are of a reference type.
 Elements can be either primitive types or reference types.
 Default values: (int:0; String: null; boolean:false)
 The length of an array can be obtained from the array
object’s length variable
 An array’s length is fixed when it is created (determines
the amount of memory allocated) and cannot be changed
unless the arraySystem.out.println(courseMarks.length);
is redeclared.
7 Lecture06
0
Array Name Index Value 1

3.Arrays courseMaks[2]= 95;


2
3
95

 Each element is accessed in constant time using an


index position of the particular element in square
brackets ([]).
 The index:
 must be an int (non-negative), or an expression that evaluates to
an int
 uses zero-numbering (indexes go from 0 to length-1)
 Array names follow the same conventions as other
variable names.
 Value (element of the array) can be accessed and
modified in constant time using its index.

8 Lecture06
3.Arrays
Declaring & Creating Arrays
 The three steps for creating an array are
 Declaring an Array int courseMarks[];
 Syntax: <type><name>[]; //or String[] args;
int[4] courseMarks;
<type>[] <name>;
Specify the size in
 No memory space allocated array declaration is a
 No length specified syntax error
 The array has not been initialized
 Creating a New Array
 <name> = new <type>[Length]; courseMarks = new int[10];
Syntax:

 specify the type of the array elements and the number of elements as part of an
array-creation expression that uses keyword new.
 returns a reference that can be stored in an array variable.
 Note: memory space allocated, length specified, initialized to default values
 Creating & Initializing elements
 create an array and initialize its elements with an array initializer — a comma-
separated list of expressions enclosed in braces.
 i.e. counts the number of initializers in the list to determine theint[]{26,73,55,97};
size of the array
courseMarks = new
 Syntax: <name> = new <type> { values };
9 Lecture06
3.Arrays
Creating Arrays
 Combine declaration and creation
 The first two steps of creating an array can be combined as one:
int[] courseMarks = new int[10];

 Combine declaration & initialization


 Array elements can be initialized in the declaration statement by putting a
comma-separated list in braces
 The length of an array is automatically determined when the values are
explicitly initialized in the declaration
int[] courseMarks = new int[4]{26,73,55,97};
double[] reading = {5.1, 3.02, 9.65};

 The memory space of an array can be allocated dynamically during


the run-time of the program.
 If the size is -1, it will lead to a run-time error
 Note: The Java compiler will NOT indicate that something is wrong.

int[] courseMarks = new int[-1];


10 Lecture06
3.Arrays
Using Arrays
 Array processing is easily done in a loop
 A for loop is commonly used to initialize array elements and print
out all values int[] reading = new int[5];
 Initialization for (int i=0; i<reading.length; i++) {
reading[i] = i;
}
 Note:
 The loop counter/array index goes from 0 to length-1
 It counts through length=5 iterations using the zero-numbering of the
array index
for (int i=0; i<reading.length; i++) {
 Printing System.out.println(reading[i]);
}

 Using an index larger than length-1 causes a run time (not


a compiler) error Outside the
 An ArrayIndexOutOfBoundsException is thrown valid range
System.out.println(reading[5]);

11 Lecture06
L06Code.jav
3.Arrays a

Example 1
 Example 1:
 creates a 10-element array and assigns to each element
one of the even integers from 2 to 20 (2, 4, 6, …, 20).
 ARRAY_LENGTH: is a constant.
 Constant variables must be initialized before they’re used and
cannot be modified thereafter.
final int ARRAY_LENGTH = 5;
int[] array = new int[ARRAY_LENGTH];

for (int counter=0; counter<array.length; counter++)


array[counter] = 2 + 2 * counter;
0 2
1 4
for (int counter=0; counter<array.length; counter++)
2 6
System.out.printf("%5d%8d%n", counter, array[counter]);
3 8
4 10

12 Lecture06
3.Arrays
Enhanced for Statement
 Iterates through the elements of an array without
using a counter, thus avoiding the possibility of
“stepping outside”
for (parameter the array.
: arrayName)
statement
 Syntax:
 where parameter has a type and an identifier, and
arrayName is the array through which to iterate.
 It can be used only to obtain array elements—it
cannot be used to modify elements.
 Note: No error message generated, the values are simply
unchanged 2
for (int value: array) 4
 If you
valueneed
+= 2; to modify elements, use the standard for
6 loop
for (int value: array) 8
System.out.printf("%5d%n", value); 10

13 Lecture06
L06Code.jav
3.Arrays a

Arguments for the method main


 The heading for the main method shows a parameter that is an array
of Strings:
public static void main(String[] args) {
...
}

 When you run a program from the command line, all words after the
class name will be passed to the main method in the args array.
>java TestArray Hello World

 The following main method in the class TestArray will print out the first
two arguments it receives:
public static void main(String[] args) { Output
for (int i=0; i<args.length; i++) :
System.out.println(args[i]);
} Hello
World

14 Lecture06
3.Arrays
Testing for Equality
 The following example creates two arrays of ints.
int[] a = new int[] {1, 2, 3}; a b
int[] b = new int[] {1, 2, 3}; 0 0 0 0
1 1 1 1
2 2
2 2

 Comparison “==”
 Compares references, not values. The use of == with array/object
references is generally limited to if two references are to the same
object
if (b == a)
Not Equal
System.out.println("Equal");
else
System.out.println("Not Equal");

 Variables a and b are both 3-element arrays of ints


 The output of this example is "Not Equal" because the addresses
of the arrays are not equal.
15 Lecture06
3.Arrays
Copying Arrays
 Note: assigning one array to another only changes the references. No
actual copying is performed.
 To perform copying, use the
 void arraycopy(Object src, int srcPos, Object dest, int
destPos, int length)
 Copies an array from the specified source array, beginning at the specified
position, to the specified position of the destination array.
int[] src = {1,2,3};
int[] copy = new int[3];
System.arraycopy(src,0, copy, 0, 2); sr cop
for (int i=0; i<copy.length; i++) c 0 1 y 0 1
System.out.println(copy[i]); 1 2 1 2
2 3 2 0

if (copy == src) //checking reference


 Note: System.out.println("Equal");
 else
It is useful when copying parts of an array
System.out.println("Not Equal");
 The copy array must be first created.
Not Equal
16 Lecture06
3.Arrays
Cloning Arrays
 To copy the entire array, use the clone method
 Object clone()
 Creates and returns a copy of this object
int[] src = {1,2,3};
int[] copy = src.clone();

Must create an
object first

sr cop if (copy == src) //checking reference


c y 0 1 System.out.println("Equal");
0 1
else
1 2 1 2
System.out.println("Not Equal");
2 3 2 3

Not Equal
17 Lecture06
Exercise 1
 What is the output of the following code fragment?
int[] array = {0, 2, 4};
for (int value: array)
value += 2;
System.out.println(Arrays.toString(array));

 What is the output of the following code fragment?


int[] array = {0, 2, 4};
for (int counter=0; counter<array.length; counter++)
array[counter] += 2;
System.out.println(Arrays.toString(array));

 What is the output of the following code fragment?


int[] array = {0, 2, 4};
for (int value: array) {
value += 2;
}
System.out.println(Arrays.toString(array));

18 Lecture06
L06Code02.jav
3.Arrays a

Pass-by-value
 All arguments are passed by value in method calls in Java.
 A method call can pass TWO types of values to a method—
copies of primitive values and copies of references to objects.
 Objects themselves cannot be passed to methods.
 Case 1: primitive types: (int, double, float.. etc)
 a copy of the argument’s value is passed to the called method.
 changes to the called method’s copy do not affect the original variable’s
value in the caller.
public static void changeMyNumber(int justACopy){
justACopy = 10;
System.out.println("justACopy = "+justACopy);
}

public static void myMethod() {


int myNumber = 12345;
String myString = "testing";
System.out.println("myNumber before call = "+myNumber);
changeMyNumber(myNumber); myNumber before call = 12345
System.out.println("myNumber after call = "+myNumber); justACopy = 10
}
19 myNumber after callLecture06
= 12345
L06Code02.jav
3.Arrays a

Pass-By-Value
 Case 2: Reference Types (StringBuffer, array… etc)
 i.e. a copy the object’s reference is passed to the called method
 an object’s reference is passed by value, a method can still interact with
the referenced object by calling its public methods using the copy of the
object’s reference.
 The parameter in the called method and the argument in the calling
method refer to the same object in memory.
 We can modify the object and have the changes reflected in the outer
scope.
public static void changeMyString(StringBuffer justACopy) {
justACopy.append("++"); ++
myString myNumb
0x25a1 er
12345
System.out.println("justACopy = "+ justACopy); c
}
copy of the object’s reference to
public static void myMethod2() { justACopy

int myNumber = 12345; changeMyString


StringBuffer myString = new StringBuffer("testing");
0x25a1
System.out.println("myString before call = "+myString); c
changeMyString(myString); myString before call = testing
System.out.println("myString after call = "+myString);
justACopy = testing++
20
} myString after call = testing++ Lecture06
L06Code02.jav
3.Arrays a

Pass-By-Value
 Case 3: Reference Types (StringBuffer, array… etc)
i.e. a copy the object’s reference is passed to the called method

 If you modify a reference-type parameter so that it refers to another
object, only the parameter refers to the new one.
 changes to the called method’s copy do not affect the original variable’s
value in the caller.
public static void makeNewString(StringBuffer justACopy) {

justACopy = new StringBuffer("another String");

System.out.println("justACopy = "+justACopy);
}

public static void myMethod3() {


int myNumber = 12345;
StringBuffer myString = new StringBuffer("testing");
System.out.println("myString before call = "+myString);
makeNewString(myString);
System.out.println("myString after call = "+myString);
}
myString before call = testing
justACopy = another String
21 myString after call = testing Lecture06
L06Code02.jav
3.Arrays a

Passing Arrays to Methods


 To pass an array argument to a method, specify the name
of the array without any brackets.
modifyArray(origArray);
 the method’s parameter list must specify an array parameter.
public static void modifyArray(int[] myArray) { ... }
 the called method receives a copy of the object’s reference.
 i.e. they both refer to the same object
 We can modify the object and have the changes reflected in the
outer scope.

public static void modifyArray(int[] myArray) {


myArray[0] += 10; origArray before call = 3
} origArray after call = 13

int[] origArray = {3,5,7};


System.out.println("origArray[0] before call = "+origArray[0]);
modifyArray(origArray);
22 System.out.println("origArray[0] after call = "+origArray[0]); Lecture06
L06Code02.jav
3.Arrays a

Passing Array elements to Methods


 To pass an individual array element of a primitive type
to a method, specify the name of the array and the
index. changeMyNumber(origArray[2]);

 the called method receives a copy of the element’s value.


 Modifying the copy in the called method does not affect the
original value of that element in the calling method’s array.
public static void changeMyNumber(int justACopy){
justACopy = 10;
System.out.println("justACopy = "+justACopy);
} origArray[2] before call = 7
justACopy = 10
origArray[2] after call = 7
int[] origArray = {3,5,7};
System.out.println("origArray[2] before call = "+origArray[2]);
changeMyNumber(origArray[2]);
System.out.println("origArray[2] after call = "+origArray[2]);

23 Lecture06
L06Code02.jav
3.Arrays a

Variable-Length Argument Lists


 With variable-length argument lists, you can create
methods that receive an unspecified number of
arguments.
 Syntax: A type followed by an ellipsis (...) in a method’s
parameter list
 e.g. double… numbers
 Note: it can occur only once in a parameter list, and
muststatic
public be placed at the end
double average(double... of the
numbers) { parameter list.
double total = 0;
 Java treats
for (double the variable-length argument list as an
d: numbers)
Average 15.0
array whose
total += d;
elements
return total/numbers.length; are all of the same
Average type.
20.0
}

System.out.printf("Average %.1f%n", average(d1, d2));


System.out.printf("Average %.1f%n", average(d1, d2, d3));
24 Lecture06
4.Multidimensional Arrays
 Multidimensional Arrays - Arrays with more than one index
 number of dimensions = number of indexes
 Multidimensional arrays with two dimensions are often used to
represent tables of values with data arranged in rows and
columns.
 To identify a particular table element, you specify two indices—the first
identifies the element’s row and the second its column.
 Multidimensional arrays can have more than two dimensions.
 Java does not support multidimensional arrays directly, but it allows you
to specify one-dimensional arrays whose elements are also one-
dimensional
int[][][] threeD =arrays,
new intthus achieving the same effect.
[2][3][4];
int[][][][] fourD = new int [2][3][768][1024];

7
int[][] x = new int[5][7];
columns:

5 rows

25 Lecture06
4.Multidimensional Arrays
2-Dimensional Arrays
 Declaration & Initialization 2-D arrays
 Syntax for 2-D arrays is similar to 1-D arrays
 <type>[][] <name> = new <type>[rows][columns];
 Example 1:
int[][] x = new int[5][7];

 The array should have five rows and seven columns


 The real picture:

 Example 2:
int[][] x = new int [4][];

 The array has 4 rows.


 2-D Array Initializer
 You can also initialize at declaration with 2D array literal
 Use nested comma separated lists, enclosed in {}’s
Compiler determine the
1 2 3 number of rows and
int[][] y = { {1,2,3}, {4,5,6}}; determine the number of
4 5 6
columns in each row
26 Lecture06
4.Multidimensional Arrays
Creating Multidimensional Arrays
 We can use existing arrays for initialization
 a3 does not store copies of a1 and a2 in Array3[0] and a3[1]
a1
respectively 0 10
 Instead it stores reference to a1 and a2
int[] a1 = {10,12,14}; a2 1 12
int[] a2 = {20,22,24}; a3 0 0 20 2 14
int[][] a3 = {a1, a2};
1 1 22
2 24

 If we change the value of a1[1], we also change the value of a3[0]


[1]a1[1] = 0;
System.out.println(a3[0][1]);

a1
 To create copies of an existing 1-dimensional arrays,
0 10 we
int[][] a4={a1.clone(), a2.clone()};
can use the clone method a2
1 12
a4 1 1 1 0 20 2 14
0
0 2 4
1 2 2 2 1 22
0 2 4
2 24
27 Lecture06
4.Multidimensional Arrays
Length Variables
 Using the Length Variable:
 arrayName.length
 returns the number of rows in the array
 arrayName[rowToGet].length
 returns the number of columns in row "rowToGet"
int[][] x = new int[5][7];
System.out.println(x.length);
System.out.println(x[0].length);
5
 Note: 7

 If x is a rectangular array, all rows have the same length


System.out.println(x[0].length); 7
System.out.println(x[1].length); 7
System.out.println(x[2].length); 7

28 Lecture06
4.Multidimensional Arrays
L06Code03.jav
a

Using 2D Arrays
 Accessing elements
 To access elements, we use pretty much the same technique as a
1D array
System.out.println(myArr[rowToGet][colToGet]);

 Initialization & Printing


 Nested loops are used to initialize array elements and print out
values
 Starting from the first row (0th) to the last row (n-1) – outer loop
 For each row, starting from theUse y.length
first to
column (0 th
) to the last
navigate the last
column (m-1) – inner loop row
 Printyout
int[][] = {the value{4,5,6} };
{1,2,3},
for (int row = 0; row < y.length; row++) {
for (int col = 0; col < y[row].length; col++)
System.out.print(y[row][col] + " ");
System.out.println(); Use y[row].length to
} navigate the last column of
each row

29 Lecture06
4.Multidimensional Arrays
Cloning of Multi-D Arrays
 It is shallow clone only
 Remember that multi-dimensional arrays in Java are arrays of arrays.
Cloning only generates a copy of the root array

int[][] a5 = {{10,12,14}, {20,22,24}};


int[][] a6 = a5.clone();
a5
1 1 1
0
0 2 4
1 2 2 2
a6 0 2 4
0
1

 Note: a5[0] and a5[1] from an 1-dimensional array that store the
memory location m0 and m1 of two 1-dimensional arrays. If we clone
a5, then we only create a new 1-dimensional array that stores m0 and
m1.

30 Lecture06
4.Multidimensional Arrays
Ragged Arrays
 Ragged arrays have rows of unequal length
 Each row has a different number of columns, or entries
 Declaration & Initialization a ragged array
 <type>[][] <name> = new <type>[rows][];
 <name>[0] = new <type>[colCountForRow1];
 … int[][] b1 = new int[2][ ];
b b1[0] = new int[]{1, 2, 3, 4, 5};
0 0 b1[1] = new int[]{1, 2, 3};
int[][] b; 0
b = new int[3][]; 0 0 0
1
b[0] = new int[2]; b 1 2 3 4 5
2 0 0
b[1] = new int[3];
b[2] = new int[1]; 1 1 2 3

 Using Array Initializer


b
int[][] b = {{3,2}, {3,2,1}, {1}}; 0 3 2
1 3 2 1
2 1
31 Lecture06
4.Multidimensional Arrays
Using Ragged Arrays
 Length Variables:
 arrayName.length returns the number of rows in the array
 arrayName[rowToGet].length returns the number of columns in row
"rowToGet" int[][] y = {{3,2}, {3,2,1}, {1}};
 Example:
 b.length = 3
 b[0].length returns 2
 b[1].length returns 3
 b[2].length returns 1
 b[3].length <- ERROR
 Initialization & Printing
 Nested loops are used to initialize array elements and print out values
 Note: You must use y[row].length to get the number of columns in each
row. The number may not be the same for all rows.
for (int row = 0; row < y.length; row++) {
for (int col = 0; col < y[row].length; col++)
System.out.print(y[row][col] + " ");
System.out.println();
32 } Lecture06
4.Multidimensional Arrays
Example: Pascal's Triangle
 Pascal’s Triangle using a ragged array
 The first row has 1 element 1
 The second row has 2 elements 1 1
1 2 1
 The third row has 3 elements 1 3 3 1
1 4 6 4 1
 ...
 The n row has (n+1) elements
 Solution:
 Create a n-row array
 Fill the first row, create 1 column and fill by 1
 For the second to the last row(n), create (n+1) columns
 Calculate the value
 For the first or last column, value = 1
 Else, value[row][col] = value of the previous row and previous col
+ value of the previous row but the same col

33 Lecture06
L06Code03.jav
4.Multidimensional Arrays a

Example: Pascal's Triangle


 Code:
final int NUM_ROWS = 5;
int triangle[][] = new int[NUM_ROWS][];
triangle[0] = new int[1];
triangle[0][0] = 1;
for (int row = 1; row < NUM_ROWS; row++) {
triangle[row] = new int[row+1];
triangle[row][0] = 1;
triangle[row][row] = 1;
for (int col = 1; col < row; col++)
triangle[row][col] = triangle[row-1][col-1] + triangle[row-1][col];
}

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

34 Lecture06
int[][] grid = { { 3, 5, 6, 9 },{ 2, 6, 9, 4 } };
Exercise 2 int len;

 What is the output of the following code fragment?


len = grid[0].length;
for(int row=0; row < len; row++) {
for(int col=0; col < len; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}

len = grid.length;
for(int row=0; row < len; row++) {
for(int col=0; col < len; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}

35 Lecture06
5.Array of Objects
 Apart from arrays of primitive types we can have arrays of reference
types (objects)
 p
Creating an array of Point 0
x:10
 Syntax: y:20
 Create the array
1 x:20
 <class>[]Point[]
<name> p == new
new <class>[Length];
Point[3];
y:30
2
 Note: Memory space are allocated for the array NULL
 Create the object element
 <name>[row] = new <class>();
p[0] = new Point(10, 20);
p[1] = new Point(20, 30);

 Note:
 In an array of reference types not the objects are stored in the array, but
references to the objects.
 The objects themselves have to be created and memory space has to be
allocated for them separately.
 The element are initialized with the null reference.
36 Lecture06
L06Code04.jav
a
5.Array of Objects
Using Array of Objects
 Accessing
 To access all components of an array of reference types
we can use the same code that we have used for
primitive types
 A for loop is used to print out values. java.awt.Point[x=10,y=20]
for (int i=0; i<2; i++)
System.out.println(p[i].toString()); java.awt.Point[x=20,y=30]

 You must create the object element before accessing it.


 Otherwise, a NullPointerException is thrown.
for (int i=0; i<p.length; i++)
System.out.println("(" + p[i].x + ","+ p[i].y + ")");

(10,20)
(20,30)
Exception in thread "main" java.lang.NullPointerException ...

37 Lecture06
5.Array of Objects L06Code04.jav
a

Assignment - Arrays of Objects


 Reference type: p x:10 -
Point[] p = new Point[3]; 0 >100
p[0] = new Point(10, 20); cop y:20
p[1] = new Point(20, 30); y 1 x:20
p[2] = new Point(30, 40);
y:30
Point[] copy = p; 2
x:30
Y:40

 The variable copy holds a copy of the reference held in the variable
p. There is still only one copy of the array.
 Thus changing the object pointed to by one of the variables will also
cause the contents of the other variable to change (since the same
object in memory is being altered).

copy[0].x = 100;
for (int i=0; i<copy.length; i++) java.awt.Point[x=100,y=20]
System.out.println(p[i].toString()); java.awt.Point[x=20,y=30]
java.awt.Point[x=30,y=40]
38 Lecture06
L06Code04.jav
a
5.Array of Objects
Copying Arrays of Objects
 An array can be copied to reproduce an exact copies (or part) of the
original by using the System.arraycopy method
 However, if the array elements are reference variables, both source and
destination now refer to the same object (pointing to the same physical
object in memory)
p x:10 -
Point[] p = new Point[3]; 0 >100
p[0] = new Point(10, 20);
p[1] = new Point(20, 30); y:20 cop
1 x:20 0 y
p[2] = new Point(30, 40);
y:30
Point[] copy = new Point[2]; 2 1
System.arraycopy(p,0, copy, 0, 2); x:30
Y:40

 Thus changing the object pointed to by one of the variables will also cause
the contents of the other variable to change (since the same object in
memory is being altered).
copy[0].x = 100;
for (int i=0; i<copy.length; i++) java.awt.Point[x=100,y=20]
System.out.println(p[i].toString()); java.awt.Point[x=20,y=30]

39 Lecture06
L06Code04.jav
a
5.Array of Objects
Cloning Arrays of Objects
 Shallow Clone
 An array can be cloned to reproduce an exact copies of
the original
 It allocates space to hold the same size as the original
 It makes copies of the original and has the same problem as
before (pointing to the same physical object in memory)

Point[] p = new Point[2]; p x:10 -


p[0] = new Point(10, 20); 0 >100
p[1] = new Point(20, 30);
y:20 cop
1 0 y
Point[] copy = p.clone(); x:20
y:30
1
copy[0].x = 100;
System.out.println(p[0].toString());
java.awt.Point[x=100,y=20]

40 Lecture06
L06Code04.jav
5.Array of Objects a

Deep Clone
 A deep copy is copy that contains the complete data of
the original object, allowing it to be used independently of
the original object
 Clone the array
 Walk through each element in the new array
 Clone the element in the array to produce a new copy

Point[] q = new Point[2];


q[0] = new Point(10, 20); q x:10 -
q[1] = new Point(20, 30); 0 x:10 dest 0
>100
y:20
Point[] dest = q.clone(); y:20
1 1 x:20
for (int i = 0; i < q.length; i++) x:20
dest[i] = (Point)q[i].clone( ); y:30
y:30

dest[0].x = 100;
System.out.println(q[0].toString()); java.awt.Point[x=10,y=20]

41 Lecture06
Advantages & Disadvantages
 Advantages
 Easy to specify (declaration, allocation of memory space,
initialization can all be done in one line of code)
 Direct access to any element via the index
 Fast Access
 Disadvantages
 A potential disadvantage of arrays is the need to know
the size at time of allocation
 Careful design is required to make sure that the array
will be large enough to hold the largest possible group of
data

42 Lecture06
Exercise 3
 Write a program that simulates rolling a pair of dice. Each die can
have the values of 1 to 6 and the sum of the dice can have values
from 2 to 12. Use a one-dimensional array to tally the number of
times each possible sum appears. The application should roll the
dice 36,000 times. Display the results in a tabular format.
int[] totals = new int[13];
int dice1, dice2;
SecureRandom randomNumbers = new SecureRandom(); Sum Frequency Percentage
2 1021 2
for (int roll = 1; roll <= 36000; roll++) { 3 1919 5
4 3032 8
5 3983 11
6 4944 13
7 6045 16
} 8 5023 13
9
System.out.printf("%3s%12s%12s\n","Sum", "Frequency", "Percentage"); 4051 11
for (int k = 2; k < totals.length; k++){ 10 2988 8
11 / (360));
System.out.printf("%3d%12d%12d%n", k, totals[k], totals[k] 1972 5
12 1022 2

43 Lecture06
Exercise 4 int[] array = {0,0,0,0,0,0,1,2,4,2,1};

 Display the following bar-chart using the array given


above:

for (int counter=0; counter<array.length; counter++) {


if (counter == 10)
System.out.print(" 100: ");
else
System.out.printf("%02d-%02d: ________, ___________);
for

System.out.println();
}

44 Lecture06

You might also like