Java Reference
In-Depth Information
public static void
main(String [] args)
{
int
a[] =
new i n t
[]
{
2,234,14,12,23,2
}
;
int
b [ ] = Arrays . copyOf(a , a. length) ;
b[3]=7;
System. out . println (a [ 3 ] ) ;
}
}
The
Arrays.copyOf
method creates a new array. The size of the new array is defined
as the second parameter of the method. The first parameter of the method specifies the
original array from which elements are copied one by one.
5.1.2 Deep versus Shallow Array Comparison
Similar to copying arrays, comparing arrays for equality is not trivial. Consider the
following simple program.
public class
Test
{
public static void
main(String [] args)
{
int
[] a =
{
2,234,14,12,23,2
}
int
[] b =
{
2,234,14,12,23,2
}
System. out . println (a==b) ;
}
}
The program creates two identical arrays and compares them for equality. The reader
might expect that the arrays should be equal and
true
should be printed. However, if we
run the program, we will see that
false
is printed. The reason is that the operator “==”
compares the locations of the arrays and not their content. For example, the
a
array can be
stored at location 1000, while the
b
array can be stored at location 2000 (see Figure 5.3).
Since the numbers 1000 and 2000 are different, the program will print
false
.
One can use the operator “==” to compare two arrays for equality. This will
compare the addresses of the two arrays and not their content. This is referred to as
shallow copy
.
If we want to properly compare the content of the two arrays, then we need to use a
for
loop. Here is an example.
public class
Test
{
public static void
main(String [] args)
{
int
[] a =
{
2,4,6,8,10
}
;
int
[] b =
{
2,4,6,8,10
}
;
System. out . println (compare(a ,b) ) ;
public static boolean
compare(
int
[] a,
int
[] b)
{
if
(a.length!=b.length)
{
return false
;
for
(
int
i=0; i
<
a . l e n g t h ;
i ++)
{
if
(a[ i ]!=b[ i ])
{
return false
;
}
}