Java Reference
In-Depth Information
A DVANCED T OPIC 7.1: Array Initialization
You can initialize an array by allocating it and then filling each entry:
int[] primes = new int[5];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
primes[4] = 11;
However, if you already know all the elements that you want to place in the array,
there is an easier way. List all elements that you want to include in the array,
enclosed in braces and separated by commas:
int[] primes = { 2, 3, 5, 7, 11 };
The Java compiler counts how many elements you want to place in the array,
allocates an array of the correct size, and fills it with the elements that you specify.
If you want to construct an array and pass it on to a method that expects an array
parameter, you can initialize an anonymous array as follows:
new int[] { 2, 3, 5, 7, 11 }
7.2 Array Lists
Arrays are a rather primitive construct. In this section, we introduce the ArrayList
class that lets you collect objects, just like an array does. Array lists offer two
significant conveniences:
292
293
The ArrayList class manages a sequence of objects.
ȗ Array lists can grow and shrink as needed
ȗ The ArrayList class supplies methods for many common tasks, such as
inserting and removing elements
Search WWH ::




Custom Search