Common Array Algorithms
This chapter discusses how a for loop can be used to iterate over the elements of a one-dimensional array. In addition, it also discusses enhanced for loops. The chapter demonstrates the use of arrays to solve common problems such as finding sum, average, maximum, and minimum values of numbers stored in array. Pay attention to some of the common programming errors one can make while using arrays.
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 |
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 |
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?