Java Reference
In-Depth Information
return true
;
}
}
Comparing the content of two arrays and not only their location is referred to as
deep
comparison
.
Comparing two arrays using the “==” operator is wrong. This will only tell us if
the arrays have the same location. In order to compare the content of two arrays, we
need to use a
for
loop that performs deep comparison of the arrays.
Since deep array comparison is such a common operation, there is a method that per-
forms it for us. Here is an example of how the method works.
import
java . util .
∗
;
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 (Arrays . equals (a , b) ) ;
}
}
The
Arrays.equals
method uses a
for
loop that iterates through the two arrays. It
returns
true
exactly when the two arrays have the same number of elements and all the
corresponding pairs of elements in the two arrays are equal.
5.2 The Trading Game Revisited
Let us use our newly acquired knowledge of arrays and refactor the trading game from
the previous chapter. Now, we will allow the trader to buy or sell multiple products. Consider
the following declaration.
class
TradingGame
{
static final int
ITEM COUNT = 2 ;
static final
String [] item =
new
String []
{
"apples"
,
"pears"
}
;
static double
price [] =
new double
[ITEMCOUNT ] ;
static int
inventory [] =
new i n t
[ITEMCOUNT ] ;
}
Now the products, their price, and the available inventory are all defined using an array.
This allows us to quickly introduce more items, if needed, by only changing the variables
ITEM COUNT
and
item
.
The new code for the
main
method follows.
import
java . text .
∗
;
import
java . util .
∗
;
public class
TradingGameArrays
{
static final int
NUMBER OF DAYS = 1 0 ;
static final double
BASE PRICE = 10;