Java Reference
In-Depth Information
This is one of only two examples we have seen in which Java will construct an
object without the new keyword. The other place we saw this was with String liter-
als, in which Java constructs String objects without your having to call new . Both of
these techniques are conveniences for programmers. These tasks are so common that
the designers of the language wanted to make it easy to do them.
The Arrays Class
Arrays have some important limitations that you should understand. Over the years
Sun has attempted to remedy these limitations by providing various utility methods
in a class called Arrays . This class provides many methods that make it easier to
work with arrays. The Arrays class is part of the java.util package, so you would
have to include an import declaration in any program that uses it.
The first limitation you should be aware of is that you can't change the size of an
array in the middle of program execution. Remember that arrays are allocated as a
contiguous block of memory, so it is not easy for the computer to expand the array. If
you find that you need a larger array, you should construct a new array and copy the
values from the old array to the new array. The method Arrays.copyOf provides
exactly this functionality. For example, if you have an array called data , you can
create a copy that is twice as large with the following line of code:
int[] newData = Arrays.copyOf(data, 2 * data.length);
If you want to copy only a portion of an array, there is a similar method called
Arrays.copyOfRange that accepts an array, a starting index, and an ending index as
parameters.
The second limitation is that you can't print an array using a simple print or
println statement. You will get odd output when you do so. The Arrays class once
again offers a solution: The method Arrays.toString returns a conveniently for-
matted version of an array. Consider, for example, the following three lines of code:
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23};
System.out.println(primes);
System.out.println(Arrays.toString(primes));
It produces the following output:
[I@fee4648
[2, 3, 5, 7, 11, 13, 17, 19, 23]
Notice that the first line of output is not at all helpful. The second line, however, allows
us to see the list of prime numbers in the array because we called Arrays.toString to
format the array before printing it.
 
Search WWH ::




Custom Search