Sie sind auf Seite 1von 6

Arrays

Java
Arrays
• An array is a collection object (consists of
a collection of data) that holds a fixed
number of values of the same data type.
Arrays
// example 1
• Each item in an
array is an int[] myArray;
element and myArray = new int[10];
each element is myArray[0] = 100; // initialize 1st element
accessed by its myArray[1] = 200; // initialize 2nd element
numerical index. myArray[2] = 300; // etc.
The first element myArray[3] = 400;
always has an myArray[4] = 500;
index of 0. myArray[5] = 600;
• Examples of myArray[6] = 700;
array myArray[7] = 800;
myArray[8] = 900;
declarations
myArray[9] = 1000;
(with sample
initialization) :
Array Examples
// example 2
int[] myArray = new int[10];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = Keyboard.readInt();
}
// example 3
int[] myArray = {15, 5, 3, 9, 25, 55, 31, 39, 65, 90};
Array Example
// import java.util.*;
int[] myArray = new int[10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
// populate array with random
values
myArray[i] = r.nextInt(100);
}
// to display the elements
for (int i = 0; i < myArray.length;
i++) {
System.out.println(myArray[i]);
}
Arrays
• The built-in length property associated
with an array return the size of an array.
• The enchanced for statement can be used
to iterate through an array in a more
compact manner. The element itself,
instead of the index, is declared as a
variable in the loop.
for (int item : myArray) {
System.out.println(item);
}

Das könnte Ihnen auch gefallen