Common Array Algorithms
22. Array Equality
Answer:
if ( array.length > 0 )
{
. . .
System.out.println("The average is: " + total / array.length );
}
else
System.out.println("The array contains no elements." );
Array Equality
Are the following two arrays equal?
int[] arrayA = { 1, 2, 3, 4 };
int[] arrayB = { 7, 8, 9};
Obviously not.
Are these two arrays equal?
int[] arrayC = { 1, 2, 3, 4 };
int[] arrayD = { 4, 3, 2, 1 };
Less obvious, but ordinarily they would not be regarded as equal.
What about these two arrays: are they equal?
int[] arrayE = { 1, 2, 3, 4 };
int[] arrayF = { 1, 2, 3, 4 };
Here, it depends on what you mean by "equal". The object referred to by the variable arrayE
is not the same object that is referred to by the variable arrayE
. The "alias detector" ==
returns false
.
class ArrayEquality { public static void main ( String[] args ) { int[] arrayE = { 1, 2, 3, 4 }; int[] arrayF = { 1, 2, 3, 4 }; if (arrayE==arrayF) System.out.println( "Equal" ); else System.out.println( "NOT Equal" ); } } Output: NOT Equal |
You have seen this situation before, with two separate
String
objects containing the same characters:
class StringEquality { public static void main ( String[] args ) { String stringE = new String( "Red Delicious"); String stringF = new String( "Red Delicious"); if (arrayE==arrayF) System.out.println( "Equal" ); else System.out.println( "NOT Equal" ); } } Output: NOT Equal |
There are two individual objects, so the object reference in
stringE
is not ==
to the object reference in stringF
.Question 22:
Confusion Alert! (review of Chapter 43)
String stringG = "Red Delicious" ; String stringH = "Red Delicious" ; if (arrayG==arrayH) System.out.println( "One Literal" ); else System.out.println( "NOT Equal" );What does the above print?