Arrays are so important that we devoted this entire page to them.
Primitive arrays may be thought of as old-school 'motels:' rooms in a line-up (with rooms numbers starting with zero!) where we can check 'people' into the rooms and find them when necessary.
Declaring/Initializing/Constructing arrays:
-
Creating from an 'Initializer List':
String stooges[] = {"Moe", "Larry", "Curly"};
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
//[] ('square braces/brackets') may follow either datatype or identifier
//Used for small-sized arrays -
Declaring/Initializing an array with 'new':
int someOddNumbers[] = new int[3]; //state the size; it is fixed thereafter someOddNumbers[0] = 1; someOddNumbers[1] = 3; someOddNumbers[2] = 5; -
Creating from an ArrayList:
ArrayList<Integer> aL = new ArrayList<Integer>(); aL.add(10); aL.add(20); aL.add(30); aL.add(40); Object[] myIntObjects = aL.toArray(); //must be stored as 'Objects' int sum = 0; //accumulator for (Object obj : myIntObjects){ int val = (int)obj; //cast back as ints sum += val; } System.out.println("Sum: " + sum);
-
Creating from a delimited String:
String avengersStr = "Thor|Iron Man|Captain America|Hulk|Dr. Strange|Black Widow|Spider-man|Hawkeye|Captain Marvel|Black Panther|Vision|Ant-Man"; String avengers[] = avengersStr.split("|"); - Although arrays are objects, they are not 'birthed' through a class constructor (no 'new'). Therefore, they are considered 'primitive' and have no methods affiliated with them. They do have an important attribute: length:
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
int len = vowels.length;
System.out.println("There are " + len + " vowels in the English language");
Printing arrays:
-
Using traditional SOPs - Questionable:
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; System.out.println(vowels); //prints 'aeiou' (without '') int[] intArr = {1, 1, 2, 3, 5, 8}; System.out.println(intArr); //prints memory address: [I@4aa298b7 //DANGER WILL ROBINSON! SOPs behave differently depending on the datatype of the array! -
Using loops - Reliable:
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; //traversing the array using 'fixed iteration' for(int ndx= 0; ndx<vowels.length; ndx++){ System.out.println(vowels[ndx]); } //traversing the array using 'for-each' loop for(char v : vowels) System.out.println(v); -
'Cheating' with Arrays class:
import java.util.Arrays; public class ArrayDemoDriver{ public static void main(String[] args){ System.out.println("=== Array Demo ==="); int primitiveArray[] = {3, 2, 1, 0, 4, 3, 2, 7}; System.out.println(Arrays.toString(primitiveArray)); }//end main method }//end ArrayDemoDriver
Helpful array Manipulations:
| User Method Call | Code |
|---|
