Contents

  1. Learning Objectives
  2. Arrays
  3. Zero-based Indices
  4. For Loops and Arrays
  5. ArrayList

Learning Objectives

  • Understand what is meant by the term collections.
  • Understand what the syntax of a generic collection means.
  • Be able to use arrays and the ArrayList class.
  • Understand and be able to use the subscript operator [ ].

Arrays

Arrays are primitives in Java. We can have an array of any data type, and they are denoted by adding square brackets [] to the end of a data type. For example, int[], double[], and String[] are telling Java that it will store an array of integers, doubles, and strings, respectively.

Arrays are very rigid in Java, and inserting and removing elements within an array requires us to allocate an entirely new array and copy the values over. In other words, it isn’t trivial.

We generally do not use arrays in day-to-day life. Instead, we use a collection, such as ArrayList and Vector. However, sometimes an array just does what it needs to do without any frills or thrills.

Before we can use an array, we must allocate memory for it, and before we can allocate memory, we must know how many elements the array needs to contain.

import java.util.Scanner;
class test {
    public static void main(String[] args) {
        int num_students;
        int[] studentids;
        int i;

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number of students: ");

        num_students = scan.nextInt();
        studentids = new int[num_students];

        for (i = 0;i < num_students;i++) {
            System.out.print("Enter student id for student #" + i + ": ");
            studentids[i] = scan.nextInt();
        }

        do {
            int stud;
            System.out.print("Which student do you want to see? ");
            stud = scan.nextInt();
            if (stud < 0) {
                break;
            }
            else if (stud >= studentids.length) {
                System.out.println("Invalid index, you gave " + stud + ", but the maximum is " + (studentids.length - 1));
            }
            else {
                System.out.println("Student #" + stud + " has ID " + studentids[stud]);
            }
        } while (true);
        scan.close();
    }
 }

The code above produces the following output.

Enter the number of students: 5
Enter student id for student #0: 12345678
Enter student id for student #1: 87654321
Enter student id for student #2: 01233210
Enter student id for student #3: 51234121
Enter student id for student #4: 11111111
Which student do you want to see? 10
Invalid index, you gave 10, but the maximum is 4
Which student do you want to see? 3
Student #3 has ID 51234121
Which student do you want to see? 2
Student #2 has ID 1233210
Which student do you want to see? -1

Arrays can be declared and initialized using curly braces {}.

class test {
   public static void main(String[] args) {
      int[] mylist = {1, 2, 3, 4, 5, 6};
      System.out.println(mylist.length);
      mylist[1] = -10
      System.out.println(mylist[1]);
   }
}

The code above produces the following result.

6
-10

You can see above, we can change the value of an element by using the assignment operator (=).

Array Lengths

We can pass arrays as parameters to a method, so knowing how many elements are in the array might be helpful. We can use the length property to see how many elements are inside of the array. No matter what, however, the first element will always start at index 0.

public int getArrayLength(int[] arr) {
   return arr.length;
}

Notice that it is NOT arr.length() [with parentheses]. Instead, it does not contain parentheses. This is called a property, which describes the length or the number of elements in an array.


Zero-based Indices

As you can see with the code above, the first element of an array starts at index 0. We use the subscript operator to get elements in the array. The array above has the following structure.


For Loops and Arrays

Stepping through an array can be done with a for loop. If we want to know the index in the body of the loop, we use the for(x;y;z) version. However, we can also step through a for loop using the for(x: y) version.

class test {
    public static void main(String[] args) {
        int[] mylist = {1, 2, 3, 4, 5, 6};
        System.out.println("Using for(x: y)");
        for (int i : mylist) {
            System.out.println(i);
        }
        System.out.println("Using for(x;y;z)");
        for (int i = 0;i < mylist.length;i++) {
            System.out.println(mylist[i]);
        }
    }
}

The code above produces the following result.

Using for(x: y)
1
2
3
4
5
6
Using for(x;y;z)
1
2
3
4
5
6

This style of for loop has no iterator, but instead, it has a variable (x) that holds the value where it currently is inside of the array or list (y).

Arrays with Reference Types

Everything we have seen up until now has been an array with a value-type. However, we can have arrays of reference types as well. The important thing to note is that the array of reference types is an array of the reference itself. For example,

class test {
   public static void main(String[] args) {
      test[] t = new test[100];
   }
}

The code has now created 100 references that refer to the class test. This does NOT mean that 100 classes have been created, instead, Java has just created memory to store where in memory those classes are. In other words, we have not yet created each class in memory.

So, now we need to create the actual class in memory, and then set the memory address in each element to where Java created the class. We can do this with a for loop.

class test {
   public static void main(String[] args) {
      test[] t = new test[100];
      for (int i = 0;i < t.length;i++) {
         t[i] = new test();
      }
   }
}

So, in the code above, the line new test[100] creates 100 references, whereas t[i] = new test() creates the class and then sets t[i] to the memory address where Java put the class–the reference.


ArrayList

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html

The ArrayList is a class developed by programmers of Java. The primitive arrays leaves a lot to be desired, which is where the ArrayList comes into play. The ArrayList makes our lives much easier, as it can be resized, elements can be removed or added, and it is all taken care of behind the scenes.

The code below demonstrates the ArrayList in Java.

import java.util.Scanner;
import java.util.ArrayList;
class test {
    public static void main(String[] args) {
        int num_students;
        ArrayList<Integer> studentids;
        int i;

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number of students: ");

        num_students = scan.nextInt();
        studentids = new ArrayList<>(num_students);

        for (i = 0;i < num_students;i++) {
            System.out.print("Enter student id for student #" + i + ": ");
            int id = scan.nextInt();
            studentids.add(id);
        }

        do {
            int stud;
            System.out.print("Which student do you want to see? ");
            stud = scan.nextInt();
            if (stud < 0) {
                break;
            }
            else if (stud >= studentids.size()) {
                System.out.println("Invalid index, you gave " + stud + ", but the maximum is " + (studentids.size() - 1));
            }
            else {
                System.out.println("Student #" + stud + " has ID " + studentids.get(stud));
            }
        } while (true);
        scan.close();
    }
 }

We can use the .add() function to add things to an ArrayList. If the ArrayList is not big enough to hold it, it will reallocate the memory to make it big enough.

Also, notice that we have to use the <Integer> instead of <int>. This is because Integer is a reference-type, and int is a value-type.

The ArrayList contains a find interface using the indexOf() function. If this function finds the value, it returns the index of where that function is inside of the ArrayList. If it cannot be found, it returns -1.

import java.util.Scanner;
import java.util.ArrayList;
class test {
    public static void main(String[] args) {
        int num_students;
        ArrayList<Integer> studentids;
        int i;

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number of students: ");

        num_students = scan.nextInt();
        studentids = new ArrayList<>(num_students);

        for (i = 0;i < num_students;i++) {
            System.out.print("Enter student id for student #" + i + ": ");
            int id = scan.nextInt();
            studentids.add(id);
        }

        do {
            int stud;
            int idx;
            System.out.print("Enter student id: ");
            stud = scan.nextInt();
            if (stud < 0) {
                break;
            }
            idx = studentids.indexOf(stud);
            System.out.println("Student is at index " + idx);
        } while (true);
        scan.close();
    }
 }

The code above produces the following output.

Enter the number of students: 4
Enter student id for student #0: 1023
Enter student id for student #1: 541
Enter student id for student #2: 3256
Enter student id for student #3: 3132
Enter student id: 3132
Student is at index 3
Enter student id: 541
Student is at index 1
Enter student id: 10
Student is at index -1
Enter student id: -1

The table below shows some functions that ArrayList supports.

FunctionDescription
add(int index, E element)Adds the element at the given index. The element at this index is move up (index + 1)
add(E element)Adds the element at the end of the ArrayList.
clear()Removes all elements in the ArrayList.
get(int index)Gets the element at the given index.
indexOf(Object value)Finds value in the ArrayList and returns the index of where it was found, or -1 if it wasn’t found.
isEmpty()Returns true if the ArrayList is empty (size() == 0), false otherwise.
remove(int index)Removes and returns the element at the given index.
remove(Object value)Removes the first element that has the given value. Returns true if an element was removed, false otherwise.
set(int index, E value)Sets the element at the index to the specified value.
size()Returns the number of elements in the ArrayList
subList(int beg, int end)Returns a new List of just the elements given by index beg (inclusively) to index end (exclusively).
toArray()
Returns an array version of the ArrayList, such as Integer[].

The following code demonstrates using an ArrayList.

import java.util.ArrayList;
import java.util.List;

class test {
    public static void main(String[] args) {
        ArrayList<test> list = new ArrayList<>();
        list.add(new test(-100, 22.5));
        list.add(new test(70, 18.425));
        list.add(new test(2, 232.15));
        list.add(new test(3, 7.0));
        list.add(new test(9, 6.235));
        list.add(new test(14, 178.005));
        list.add(new test(12, 0.5));

        for (int i = 0;i < list.size();i++) {
            test t = list.get(i);
            String out = String.format("[%3d] I: %5d  D: %10.3f", 
                                i, t.getIntField(), t.getDoubleField());
            System.out.println(out);
        }
        System.out.println("Set 3");
        list.set(3, new test(-1111, -111.111));
        for (int i = 0;i < list.size();i++) {
            test t = list.get(i);
            String out = String.format("[%3d] I: %5d  D: %10.3f", 
                                i, t.getIntField(), t.getDoubleField());
            System.out.println(out);
        }
        List<test> split = list.subList(3, 6);
        System.out.println("Sub list from 3 to 6");
        for (int i = 0;i < split.size();i++) {
            test t = split.get(i);
            String out = String.format("[%3d] I: %5d  D: %10.3f",
                                i, t.getIntField(), t.getDoubleField());
            System.out.println(out);
        }
        System.out.println("Remove index 3");
        list.remove(3);
        for (int i = 0;i < list.size();i++) {
            test t = list.get(i);
            String out = String.format("[%3d] I: %5d  D: %10.3f", 
                                i, t.getIntField(), t.getDoubleField());
            System.out.println(out);
        }
        System.out.println("Clear the list");
        list.clear();
        for (int i = 0;i < list.size();i++) {
            test t = list.get(i);
            String out = String.format("[%3d] I: %5d  D: %10.3f", 
                                i, t.getIntField(), t.getDoubleField());
            System.out.println(out);
        }
    }

    public test(int i, double d) {
        this.mIntField = i;
        this.mDoubleField = d;
    }
    public void setIntField(int to) {
        this.mIntField = to;
    }
    public int getIntField() {
        return this.mIntField;
    }
    public void setDoubleField(double to) {
        this.mDoubleField = to;
    }
    public double getDoubleField() {
        return this.mDoubleField;
    }
    public boolean equals(test rhs) {
        return (this.mIntField == rhs.mIntField) &&
                (this.mDoubleField == rhs.mDoubleField);
    }
    private int mIntField;
    private double mDoubleField;
}

The code above produces the following output.

[  0] I:  -100  D:     22.500
[  1] I:    70  D:     18.425
[  2] I:     2  D:    232.150
[  3] I:     3  D:      7.000
[  4] I:     9  D:      6.235
[  5] I:    14  D:    178.005
[  6] I:    12  D:      0.500
Set 3
[  0] I:  -100  D:     22.500
[  1] I:    70  D:     18.425
[  2] I:     2  D:    232.150
[  3] I: -1111  D:   -111.111
[  4] I:     9  D:      6.235
[  5] I:    14  D:    178.005
[  6] I:    12  D:      0.500
Sub list from 3 to 6
[  0] I: -1111  D:   -111.111
[  1] I:     9  D:      6.235
[  2] I:    14  D:    178.005
Remove index 3
[  0] I:  -100  D:     22.500
[  1] I:    70  D:     18.425
[  2] I:     2  D:    232.150
[  3] I:     9  D:      6.235
[  4] I:    14  D:    178.005
[  5] I:    12  D:      0.500
Clear the list