- Like Perl, Java has a built in array class which you can use to hold multiple values so long as those values areof the same data type.
- However, in Java, arrays are much morerestrictive. For example, you may not change the size of anarray once you have created it. To add elements to an array dynamicallyyou actually have to create a new, larger array and copy the old arrayinto 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.utilpackage.
- However, for cases in which you do not need to dynamically resize your data structure, arrays workgreat. Like Perl, Java provides a zero-based array which isdefined 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 anarray 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 arrayat time of initialization such as in the following example:
int[] intArray = {0,1,2,3,4}; Previous Page |Next Page
|