Arrays

  • store one data type
  • have fixed size
  • denoted with {}
dataType[] arrayName = new dataType[numberOfItems];
int[] arraySample = {1,3,5,7,9};

Hack 1

How do we access the even numbers in arrayOne from above?

int[] arrayOne = {1, 3, 5, 7, 9};
for(int i = 0; i < arrayOne.length; i++) {
    System.out.println(arrayOne[i]);
}
1
3
5
7
9

Traversing arrays

  • done with using loops
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};

for (int i = 0; i < myFruits.length; i++) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
Fruit number 0 is Apple
Fruit number 1 is Strawberry
Fruit number 2 is Watermelon
Fruit number 3 is Blueberry

Possible errors

  • a bound error where ArrayIndexOutOfBoundsException happens is when loops are being used
  • loops through more than there are elements in the array
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};

for (int i = 0; i < myFruits.length+1; i++) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
Fruit number 0 is Apple
Fruit number 1 is Strawberry
Fruit number 2 is Watermelon
Fruit number 3 is Blueberry
---------------------------------------------------------------------------
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
	at .(#22:1)
class Main {
 
    static int length;
 
    public static void printArray(int[] array)
    {
      
        for (int i = 0; i < length; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    public static void sortArray(int[] array)
    {
        int temporary = 0;

        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                if (array[i] > array[j]) {
                    temporary = array[i];
                    array[i] = array[j];
                    array[j] = temporary;
                }
            }
        }

        System.out.println(
            "Elements of array sorted in ascending order: ");
        printArray(array);
    }

    public static void main(String[] args)
    {

        int[] array = new int[] { -5, -9, 8, 12, 1, 3 };

        length = array.length;

        sortArray(array);
    }
}
Main.main(null);
Elements of array sorted in ascending order: 
-9 -5 1 3 8 12 

Enhanced for loops for arrays

  • are for loops that can only go forward
for (dataType i: arrayName) {
  System.out.print("hi");
}

Making algorithms with arrays

  • use array.length to find number of elements in an array
  • to find a specific element, do arrayname[element number]

ie: finding sum

int[] array = {3, 2, 4, 17};

int sum  = 0; 

for (int number: array) { 
    sum += number; 
}

System.out.println(sum);
26

frq

public void addMembers(String[] names, int gradYear)
{
  for(String name : names)
    memberList.add(new MemberInfo(name, gradYear, true));
}