Sprint View

FRQ - ArrayLists

8 min read
  • Step 1: Declare Method Header:
  • Step 2: Iterate Through the Array:
  • 3. Create and add objects:
  • 4. Complete the Method
  • CollegeBoard Solution
  • 1. Reverse Iteration
  • 2. Conditional Check
  • 3. Removal from memberList
  • Part B
  • ArrayList Methods Cheat Sheet

    1. Creating an ArrayList

    ArrayList<"Type"> list = new ArrayList<"Type">();
    

    2. Common Methods

    // Add Elements
    list.add(value); // Appends a value to the end.  
    list.add(index, value); // Inserts value at a specific index.
    
    // Access Elements
    list.get(index); // Returns the element at the specified index.
    
    // Update Elements
    list.set(index, value); // Replaces the element at index with value.
    
    // Remove Elements
    list.remove(index); // Deletes element at index.  
    list.remove(value); // Deletes the first occurrence of value.
    
    // Size of the List
    list.size(); // Returns the number of elements.
    
    // Check for Elements
    list.contains(value); // Returns true if value is in the list.  
    list.indexOf(value); // Returns the index of the first occurrence of value, or -1 if not found.
    

    ArrayList Loops Cheat Sheet

    1. Traversing an ArrayList

    You can use for loops or for-each loops to iterate through an ArrayList.

    // Basic for loop
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i)); // Access element at index i
    }
    

    2. Using a For-Each Loop

    Simplified syntax, no index access.

    for (Type item : list) {
        System.out.println(item); // Access each element directly
    }
    

    3. Modifying Elements

    Use a for loop if you need to update values.

    for (int i = 0; i < list.size(); i++) {
        list.set(i, list.get(i) + 1); // Example: Increment each element
    }
    

    4. Avoid Concurrent Modification Exception

    Cannot modify ArrayList (add/remove elements) during a for-each loop. Use an iterator or a for loop for such operations.

    // Correct usage with a for loop
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) < 0) {
            list.remove(i);
            i--; // Adjust index after removal
        }
    }
    

    5. Nested Loops with ArrayLists

    Use nested loops to compare or process multiple elements.

    for (int i = 0; i < list.size(); i++) {
        for (int j = i + 1; j < list.size(); j++) {
            if (list.get(i).equals(list.get(j))) {
                System.out.println("Duplicate: " + list.get(i));
            }
        }
    }
    

    The FRQ

    1. A high school club maintains information about its members in a MemberInfo object. A MemberInfo object stores a club member’s name, year of graduation, and whether or not the club member is in good standing. A member who is in good standing has fulfilled all the responsibilities of club membership.

    A partial declaration of the MemberInfo class is shown below.

    public class MemberInfo
    {
    /** Constructs a MemberInfo object for the club member with name name,
    * graduation year gradYear, and standing hasGoodStanding.
    */
    public MemberInfo (String name, int gradYear, boolean hasGoodStanding)
    { /* implementation not shown */ }
    
    / ** Returns the graduation year of the club member. */
    public int getGradYear ()
    { /* implementation not shown */ }
    
    / ** Returns true if the member is in good standing and false otherwise. */
    public boolean inGoodStanding()
    { /* implementation not shown */ }
    
    // There may be instance variables, constructors, and methods that are not shown.
    
    }
    
    The ClubMembers class maintains a list of current club members. The declaration of the
    ClubMembers class is shown below.
    
    public class ClubMembers
    {
    
    *
    
    private ArrayList<MemberInfo> memberList;
    
    /** Adds new club members to memberList, as described in part (a).
    Precondition: names is a non-empty array. **/
    }
    
    public void addMembers (String[] names, int gradYear)
    { /* to be implemented in part (a) */ }
    
    /** Removes members who have graduated and returns a list of members who have graduated
    * and are in good standing, as described in part (b).
    */
    public ArrayList<MemberInfo> removeMembers (int year)
    { /* to be implemented in part (b) */ }
    
    // There may be instance variables, constructors, and methods that are not shown.
    
    
    

    Penalties:

    1. Array/Collection Access Confusion

    Make sure is use [] for arrays and .get(index) for ArrayList.

    int[] arr = {1, 2, 3};
    System.out.println(arr[0]); // Correct for arrays
    
    ArrayList<Integer> list = new ArrayList<>();
    list.add(10);
    System.out.println(list.get(0)); // Correct for ArrayLists
    
    

    2. Extraneous Code:

    • Avoid unnecessary code that doesn’t align with the problem’s requirements
    • This would include unnecessary pringting or extra logic

    3. Local variables used but not declared

    • always declare local variables before using them
    int total = 0; // Declare the variable first
    total += 5;    // Use it after declaration
    
    

    4. Destruction of Persistent data

    • Don’t unintentionally modify objects passed as parameters unless explicitly asked.

    5. Void method returning

    • Methods declared void cannot return a value. return type specified in the method signature

    Free Points

    1. Declare class header

    • always begin with a correct class declaration:
    public class ClubMembers {
        // Class content here
    }
    

    2. Declare variables

    • Ensure to identitfy and declare the necessary instance variables
    • The problem above specifies that the memberList as an ArrayList of MemberInfo objects:
    private ArrayList<MemberInfo> memberList;
    

    3. Constructor

    • Ensure that ClubMembers constructor initializes memberList:
    public ClubMembers() {
        memberList = new ArrayList<>();
    }
    
    

    4. length/size confusion for array

    • length/size confusion for array, String, List, or ArrayList with or without () Extraneous [] when referencing entire array

    Part A

    Write the ClubMembers method addMembers, which takes two parameters. The first parameter is a String array containing the names of new club members to be added. The second parameter is the graduation year of all the new club members. The method adds the new members to the memberList instance variable. The names can be added in any order. All members added are initially in good standing and share the same graduation year, gradYear.

    Complete the addMembers method.

    • Adds new club members to memberList, as described in part (a).
    • Precondition: names is a non-empty array.
    • public void addMembers (String[] names, int gradYear)

    Helpful Acronym

    P.L.A.N

    1. P: Parameter and Return Type
    2. L: Loop Through Data
    3. A: Apply Logic
    4. N: New/Updated Array/ArrayList

    Step 1: Declare Method Header:

    • The question specifies the method name, parameter types, and return type
    public void addMembers(String[] names, int gradYear) {
        // Method implementation
    }
    

    Step 2: Iterate Through the Array:

    • Must iterate through the array
    for (String name : names) {
        // Process each name
    }
    

    Losing points:

    • Points will be lost of they fail to access elements of the array even if the loop bounds are correct.

    3. Create and add objects:

    • For each name a new MemberInfo object should be created
    • It should then be added to memberList. The MemberInfo constructor takes three arguements:
    • Name(String)
    • Graduation year(int)
    • Good standing(boolean, should default to true)
    MemberInfo newMember = new MemberInfo(name, gradYear, true);
    

    4. Complete the Method

    • MemberInfo objects adds to memberList
    • You can still earn points even if instantiate MemberInfo objects incorrectly
    memberList.add(newMember);
    

    CollegeBoard Solution

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

    FRQ Part B - Key Points

    1. Reverse Iteration

    The loop iterates backward (i = memberList.size() - 1; i >= 0; i--) because removing elements from a list while iterating forward can cause index shifting issues, leading to skipped elements or runtime errors.

    2. Conditional Check

    Two conditions are checked:

    • Graduation Year (getGradYear()): Ensures members meet the graduation year cutoff.
    • Good Standing (inGoodStanding()): Adds members to the removed list only if they’re in good standing.

    3. Removal from memberList

    Members are removed regardless of whether they’re in good standing, provided they meet the graduation year condition.

    Part B

    Write the ClubMembers method removeMembers, which takes the following actions.

    • Returns a list of all students who have graduated and are in good standing. A member has graduated if the member’s graduation year is less than or equal to the method’s year parameter. If no members meet these criteria, an empty list is returned.

    • Removes from memberList all members who have graduated, regardless of whether or not they are in good standing.

    Step 1: Parameter and Return Type

    The identified return type is an ArrayList, which is given to us in the start of the method.

    public ArrayList<MemberInfo> removeMembers(int year) {
        
    }
    

    Step 2: Loop Through Data

    The problem tell us to both return a list of graduated students with a good standing, and remove all graduated students from the list. We will need to loop through the memberList provided to us to accomplish this using reverse iteration.

    public ArrayList<MemberInfo> removeMembers(int year) {
        for(int i = memberList.size() - 1; i >= 0; i++) {
    
        }
    }
    

    Step 3: Apply Logic

    Now, how can we determine whether the members have graduated or are in good standing? This is where logic comes in.

    We check the member’s graduation year, and check if it is less than or equal to the current year to see if they have graduated or not. Then, we check if they are in good standing. Then, regardless of whether they are in good standing or not, we remove them from the memberList.

    public ArrayList<MemberInfo> removeMembers(int year) {
        for(int i = memberList.size() - 1; i >= 0; i++) {
            if (memberList.get(i).getGradYear() <= year) {
                if (memberList.get(i).inGoodStanding) {
                }
                memberList.remove(i);
            }
        }
    }
    

    Step 4: New/Updated Array/ArrayList

    Now, we need to find a way to return all of the graduated students with a good standing in a new ArrayList. We can define a new ArrayList “graduated”, and use .add to add the members that pass both of our previous if statements to add them to the ArrayList, and return the final ArrayList after exiting the loop, matching our defined return type.

    public ArrayList<MemberInfo> removeMembers(int year) {
        ArrayList<MemberInfo> graduated = new ArrayList<MemberInfo>();
        for(int i = memberList.size() - 1; i >= 0; i++) {
            if (memberList.get(i).getGradYear() <= year) {
                if (memberList.get(i).inGoodStanding) {
                    graduated.add(memberList.get(i));
                }
                memberList.remove(i);
            }
        return graduated;
        }
    }
    

    Course Timeline