Java Reference
In-Depth Information
PITFALL: (continued)
even though c and d contain the same integers in the same indexed variables.
A comparison using == will say they are not equal because == checks only the
contents of the array variables c and d , which are memory addresses, and c and d
contain different memory addresses.
If you want to test two arrays to see if they contain the same elements, then you
can defi ne an equalArrays method for the arrays, just as you defi ned an equals
method for a class. Display 6.3 contains one possible defi nition of equalArrays for
arrays in a small demonstration class.
Self-Test Exercises
7. Consider the following class defi nition:
public class SomeClass
{
public static void doSomething( int n)
{
<Some code goes in here.>
}
<The rest of the definition is irrelevant to this question.>
Which of the following are acceptable method calls?
int[] a = {4, 5, 6};
int number = 2;
SomeClass.doSomething(number);
SomeClass.doSomething(a[2]);
SomeClass.doSomething(a[3]);
SomeClass.doSomething(a[number]);
SomeClass.doSomething(a);
8. Write a method defi nition for a static void method called oneMore , which has
a formal parameter for an array of integers and increases the value of each array
element by one. (The defi nition will go in a class, but you need only give the
method defi nition.)
9. Write a method named outOfOrder that takes as a parameter an array of double
and returns a value of type int . This method will test the array for being out of
order, meaning that the array violates the condition:
a[0] <= a[1] <= a[2] <= ...
 
Search WWH ::




Custom Search