ArraysList Overview

Important Vocabulary

Array is a data structure used to implement a list of primitive or object data Element is a single value within the array The index of an element is the position of the element within the array - For Java, the first element 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 list is at index list.length - 1

2017 FRQ #1

View FRQ here

Syntax to remember

  • This part importantly declares an array and references the ‘.add’ function

Remember the syntax:

// declare the array list
[arrayListName] = new ArrayList<Integer>();

// add to the list
[arrayListName].add([position], [value])
// ---OR---
[arrayListName].add([value])

// get from the list at a position
[arrayListName].get([position]);

// modify a list at a specific position
[arrayListName].set([position], [value]);

// get the size of an array
[arrayListName].size();

// not pertaining to arrays but still good to know
// the .intValue() method is used to convert an object of a wrapper class for primitive types (such as Integer, Double, Float, etc.) into its corresponding primitive int value.
Integer integerValue = new Integer(10); // Creating an Integer object with value 10
int intValue = integerValue.intValue(); // Extracting the int value from the Integer object
// This is needed because java arrayLists store wrapper objects for 'int' primitive values
public class Digits
{
    private ArrayList<Integer> digitList;

    // Part (a)
    public Digits(int num)
    {
        digitList = new ArrayList<Integer>();
        if (num == 0)
        {
            digitList.add(new Integer(0));
        }
        while (num > 0)
        {
            digitList.add(0, new Integer(num % 10));
            num /= 10;
        }
    }

    // Part (b)
    public boolean isStrictlyIncreasing()
    {
        for (int i = 0; i < digitList.size()-1; i++)
        {
            if (digitList.get(i).intValue() >= digitList.get(i+1).intValue())
            {
                return false;
            }
        }
        return true;
    } 
} 

Common Mistakes

  1. Failure to use the intValue() method.
    • This is important because Java by default stores data in arrayLists using wrapper classes liek Interger. In this case the wrapper class needs to be converted into a primitive int datatype to perform operations on it.
  2. Failure to use num % 10 or num /= 10.
    • These lines are meant to target the last digit to either add to the arrayList or to remove from the integer

(a) Definition and Significance of Arrays in Java

An array in Java is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created and cannot be changed after creation. Each item in an array is called an element, and each element is accessed by its numerical index, with the first element being at index 0.

Significance and Usefulness: Arrays are fundamental data structures in programming, used to store collections of data. They are particularly useful when there is a need to organize data for easy access by a numeric index. Here are some key points that highlight the significance of arrays:

  • Efficiency: Arrays are stored in contiguous memory locations, which makes accessing elements by their index very efficient.
  • Simplicity: Arrays provide a straightforward way to implement and manage collections of variables of the same type.
  • Use Cases: Arrays are used in a wide range of applications, from simple data storage to being the building blocks for more complex data structures. They are especially useful in scenarios where the number of elements is known beforehand, and elements need to be quickly accessed by index.
  • Looping: Arrays can be easily iterated over using loops, making them ideal for processing collections of data.

(b) Code: calculateAverageGrade Method

Here is how the calculateAverageGrade method can be implemented. This method calculates the average grade from an array of integers representing student grades.

public class StudentManagementSystem {
    
    /**
     * Calculates the average grade for an array of grades.
     * 
     * @param grades An array of integers representing student grades.
     * @return The average grade as a double.
     */
    public static double calculateAverageGrade(int[] grades) {
        if (grades == null || grades.length == 0) {
            // Return 0.0 if the grades array is null or empty.
            return 0.0;
        }
        
        double sum = 0; // Initialize sum of all grades to 0.
        
        // Iterate over each grade in the array and add it to the sum.
        for (int grade : grades) {
            sum += grade;
        }
        
        // Calculate the average by dividing the total sum by the number of grades.
        double average = sum / grades.length;
        
        // Return the calculated average.
        return average;
    }
    
    // Example usage
    public static void main(String[] args) {
        int[] studentGrades = {90, 85, 92, 78, 65, 88}; // Example array of grades
        double averageGrade = calculateAverageGrade(studentGrades);
        
        System.out.println("Average Grade: " + averageGrade);
    }
}

StudentManagementSystem.main(null);
Average Grade: 83.0

Explanation:

  • The calculateAverageGrade method takes an array of integers grades as its parameter.
  • The method first checks if the grades array is null or empty (grades.length == 0) and returns 0.0 in such cases to avoid division by zero or processing an invalid array.
  • It then iterates over each grade in the array, adding each grade to a cumulative sum.
  • After iterating through all grades, the method calculates the average by dividing the total sum by the number of grades in the array.
  • The calculated average is returned as a double. This ensures that the average is precise even when the division result is not a whole number.