|
|
Arrays
Arrays
- Like Perl,
Java provides an array class which can hold components
of the same primitive data type or object type.
- You may not change the size of an
array once you have created it. To add elements to an array dynamically
you actually have to create a new, larger array and copy the old array
into the new one using arrayCopy() in the java.lang.System
class.
- For a dynamically resizable data structure,
you may want to look to the Vector class in the java.util
package.
- However, for cases in which you do
not need to dynamically resize your data structure, arrays work
great. Like Perl, Java provides a zero-based array which is
defined much as variables are. You first declare what type of
data will be stored in an array, give the array a name, and
then define how large it is. Consider the following example:
int[] intArray = new int[50];
- This array would hold 50 ints numbered
from 0-49.
- Filling and extracting values from an
array is the same process as it was for Perl. Consider the
following example:
int[] intArray = new int[50];
for (int i = 0; i < 50; i++)
{
intArray[i] = i;
}
for (int i = 0; i < 50; i++)
{
System.out.println("Value: " + intArray[i]);
}
- Java also allows you to define an array
at time of initialization such as in the following example:
int[] intArray = {0,1,2,3,4};
Additional Resources:
Strings
Table of Contents
Operators
|
|