Home Collegeboard - Arrays
Post
Cancel

Collegeboard - Arrays

Intro into Arrays

  • An array is a data structure used to implement a collection (list) of primitive or object reference data.

  • An element is a single value in the array

  • The **index** of an element is the position of the element in the array

    • In java, the first element of an array is at index 0.
  • The length of an array is the number of elements in the array.

    • length is a public final data member of an array

      • Since length is public, we can access it in any class!

      • Since length is final we cannot change an array’s length after it has been created

    • In Java, the last element of an array named list is at index list.length -1

A look into list Memory

int [] listOne = new int[5];

This will allocate a space in memory for 5 integers.

1
2
ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

Using the keyword new uses the default values for the data type. The default values are as follows:

Data TypeDefault Value
byte(byte) 0
short(short) 0
int0
double0.0
booleanfalse
char‘\u0000’

What do we do if we want to insert a value into the array?

listOne[0] = 5;

Gives us the following array:

1
2
ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

What if we want to initialize our own values? We can use an initializer list!

int [] listTwo = {1, 2, 3, 4, 5};

Gives us the following array:

1
2
ARRAY: [1, 2, 3, 4, 5]
INDEX:  0  1  2  3  4

If we try to access an index outside of the range of existing indexes, we will get an error. But why? Remember the basis of all programming languages is memory. Because we are trying to access a location in memory that does not exist, java will throw an error (ArrayIndexOutOfBoundsException).

How do we print the array? Directly printing the array will not work, it just prints the value of the array in memory. We need to iterate through the array and print each value individually!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* lets take a look at the above */

int [] listOne = new int[5]; // Our list looks like [0, 0, 0, 0, 0]

listOne[2] = 33; // Our list looks like [0, 0, 33, 0, 0]
listOne[3] = listOne[2] * 3; // Our list looks like [0, 0, 33, 99, 0]

try {
    listOne[5] = 13; // This will return an error
} catch (Exception e) {
    System.out.println("Error at listOne[5] = 13");
    System.out.println("ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!");
}


System.out.println(listOne); // THIS DOES NOT PRINT THE LIST!! It prints the value in memory
System.out.println(listOne[2]); // This will actually print the vaules in the array
1
2
3
4
Error at listOne[5] = 13
ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!
[I@2c4e18a1
33

Popcorn Hacks!

Write code to print out every element of listOne the following

1
2
3
for (int i = 0; i < 5; i++) {
  System.out.println(listOne[i]);
}
1
2
3
4
5
0
0
33
99
0

Reference elements

Lists can be made up of elements other than the default data types! We can make lists of objects, or even lists of lists! Lets say I have a class Student and I want to make a list of all students in the class. I can do this by creating a list of Student objects.

1
2
Student [] classList;
classList new Student [3];

Keep in mind, however, that the list won’t be generated with any students in it. They are initialized to null by default, and We need to create the students and then add them to the list ourselves.

1
2
3
classList[0] = new Student("Bob", 12, 3.5);
classList[1] = new Student("John", 11, 4.0);
classList[2] = new Student("Steve", 10, 3.75);

Popcorn hacks!

Use a class that you have already created and create a list of objects of that class. Then, iterate through the list and print out each object using: 1) a for loop 2) a while loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Person {
  private String name;
  private int age;
  private double grade;

  public Person(String name, int age, double grade) {
    this.name = name;
    this.age = age;
    this.grade = grade;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public int getAge() {
    return age;
  }

  public void setGrade(double grade) {
    this.grade = grade;
  }

  public double getGrade() {
    return grade;
  }

  public static void main(String [] args) {
    Person[] personList = new Person[3];

    personList[0] = new Person("Bob", 12, 3.5);
    personList[1] = new Person("John", 11, 4.0);
    personList[2] = new Person("Steve", 10, 3.75);

    System.out.println("For Loop: ");
    for (Person person : personList) {
      System.out.println("\tName: " + person.getName());
      System.out.println("\tAge: " + person.getAge());
      System.out.println("\tGrade: " + person.getGrade());
      System.out.println("\t---");
    }
    System.out.println(" ");
    System.out.println("While Loop: ");
    int i = 0;
    while (i < personList.length) {
      Person person = personList[i];
      System.out.println("\tName: " + person.getName());
      System.out.println("\tAge: " + person.getAge());
      System.out.println("\tGrade: " + person.getGrade());
      System.out.println("\t---");
      i++;
    }
  }
}
Person.main(null);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
For Loop: 
	Name: Bob
	Age: 12
	Grade: 3.5
	---
	Name: John
	Age: 11
	Grade: 4.0
	---
	Name: Steve
	Age: 10
	Grade: 3.75
	---
 
While Loop: 
	Name: Bob
	Age: 12
	Grade: 3.5
	---
	Name: John
	Age: 11
	Grade: 4.0
	---
	Name: Steve
	Age: 10
	Grade: 3.75
	---

Enhanced for loops

The enhanced for loop is also called a for-each loop. Unlike a “traditional” indexed for loop with three parts separated by semicolons, there are only two parts to the enhanced for loop header and they are separated by a colon.

The first half of an enhanced for loop signature is the type of name for the variable that is a copy of the value stored in the structure. Next a colon separates the variable section from the data structure being traversed with the loop.

Inside the body of the loop you are able to access the value stored in the variable. A key point to remember is that you are unable to assign into the variable defined in the header (the signature)

You also do not have access to the indices of the array or subscript notation when using the enhanced for loop.

These loops have a structure similar to the one shown below:

1
2
3
4
5
6
for (type declaration : structure )
{
    // statement one;
    // statement two;
    // ...
}

Popcorn Hacks!

Create an array, then use a enhanced for loop to print out each element of the array.

1
2
3
4
5
6
7
8
9
int [] list = new int[3];

list[0] = 1;
list[1] = 2;
list[2] = 3;

for (int num : list) {
  System.out.println(num);
}
1
2
3
1
2
3

Min maxing

It is a common task to determine what the largest or smallest value stored is inside an array. in order to do this, we need a method that can ake a parameter of an array of primitive values (int or double) and return the item that is at the appropriate extreme.

Inside the method of a local variable is needed to store the current max of min value that will be compared against all the values in the array. you can assign the current value to be either the opposite extreme or the first item you would be looking at.

You can use either a standard for loop or an enhanced for loop to determine the max or min. Assign the temporary variable a starting value based on what extreme you are searching for.

Inside the for loop, compare the current value against the local variable, if the current value is better, assign it to the temporary variable. When the loop is over, the local variable will contain the approximate value and is still available and within scope and can be returned from the method.

Popcorn Hacks!

Create two lists: one of ints and one of doubles. Use both a standard for loop and an enhanced for loop to find the max and min of each list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
public class MinMax {
  public static void main(String[] args) {
    int[] integerArray = {1, 5, 2, 26, 23, 8};

    int maxInt = Integer.MIN_VALUE;
    int minInt = Integer.MAX_VALUE;

    for (int i = 0; i < integerArray.length; i++) {
      int num = integerArray[i];
      if (num > maxInt) {
        maxInt = num;
      }
      if (num < minInt) {
        minInt = num;
      }
    }
    
    int maxInt2 = Integer.MIN_VALUE;
    int minInt2 = Integer.MAX_VALUE;

    for (int num : integerArray) {
      if (num > maxInt2) {
        maxInt2 = num;
      }
      if (num < minInt2) {
        minInt2 = num;
      }
    }

    System.out.println("Integer Array: ");
    for (int num : integerArray) {
      System.out.print(num + " ");
    }
    System.out.println(" ");
    System.out.println(" ");
    System.out.println("For Loop: ");
    System.out.println("\nMaximum Integer: " + maxInt);
    System.out.println("Minimum Integer: " + minInt);
    System.out.println(" ");
    System.out.println("Enhanced For Loop: ");
    System.out.println("\nMaximum Integer: " + maxInt2);
    System.out.println("Minimum Integer: " + minInt2);

    double[] doubleArray = {1.37, 2.850, 45.21, 36.233, 23.2137, 3.713};

    double maxDouble = Double.NEGATIVE_INFINITY;
    double minDouble = Double.POSITIVE_INFINITY;

    for (int i = 0; i < doubleArray.length; i++) {
      double num = doubleArray[i];
      if (num > maxDouble) {
        maxDouble = num;
      }
      if (num < minDouble) {
        minDouble = num;
      }
    }
    
    double maxDouble2 = Double.NEGATIVE_INFINITY;
    double minDouble2 = Double.POSITIVE_INFINITY;

    for (double num : doubleArray) {
      if (num > maxDouble2) {
        maxDouble2 = num;
      }
      if (num < minDouble2) {
        minDouble2 = num;
      }
    }

    System.out.println(" ");
    System.out.println("Double Array: ");
    for (double num : doubleArray) {
      System.out.print(num + " ");
    }
    System.out.println(" ");
    System.out.println(" ");
    System.out.println("For Loop: ");
    System.out.println("\nMaximum Double: " + maxDouble);
    System.out.println("Minimum Double: " + minDouble);
    System.out.println(" ");
    System.out.println("Enhanced For Loop: ");
    System.out.println("\nMaximum Double: " + maxDouble2);
    System.out.println("Minimum Double: " + minDouble2);
  }
}

MinMax.main(null);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Integer Array: 
1 5 2 26 23 8  
 
For Loop: 

Maximum Integer: 26
Minimum Integer: 1
 
Enhanced For Loop: 

Maximum Integer: 26
Minimum Integer: 1
 
Double Array: 
1.37 2.85 45.21 36.233 23.2137 3.713  
 
For Loop: 

Maximum Double: 45.21
Minimum Double: 1.37
 
Enhanced For Loop: 

Maximum Double: 45.21
Minimum Double: 1.37

Hacks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Scanner;

public class ListCalc {
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("Welcome to MinMaxMedian Calc. Press enter to continue.");
    String a = scan.nextLine();
    
    if (a.equals("")) {
      System.out.println("Enter the number of integers you want in your list.");
      int n = scan.nextInt();

      int max = Integer.MIN_VALUE;
      int min = Integer.MAX_VALUE;
      int[] vals = new int[n];

      for (int i = 0; i < n; i++) {
        System.out.println("Enter number " + (i + 1));
        int num = scan.nextInt();
        max = Math.max(max, num);
        min = Math.min(min, num);
        System.out.println("You entered: " + num);
        vals[i] = num;
      }

      int median;
      if (n % 2 == 0) {
        int middle1 = vals[n / 2 - 1];
        int middle2 = vals[n / 2];
        median = (middle1 + middle2) / 2;
      } else {
        median = vals[n / 2];
      }

      System.out.println("Result: " + (max + min + median) + " " + (max - min - median) + " " + ((max + min) * median));
    }
  }
}

ListCalc.main(null);
1
2
3
4
5
6
7
8
9
Welcome to MinMaxMedian Calc. Press enter to continue.
Enter the number of integers you want in your list.
Enter number 1
You entered: 1
Enter number 2
You entered: 8
Enter number 3
You entered: 4
Result: 17 -1 72
This post is licensed under CC BY 4.0 by the author.

Class Structure

Plan 10