Lesson Purpose and Objectives

Learn about the structure and functions of an arrayList and go over the key College Board concepts for arrayLists

ArrayLists are only 2.5%-7.5% but have many concepts from other units and are a good data structure to know. Also, the 3rd question of the FRQ is based on ArrayLists

7.1 Introduction to ArrayList

Arrays ArrayLists
Static (fixed size) Dynamic (can change size)
Fundamental java feature Part of a framework. Someone was nice and designed this with the behind the scenes being arrays
An object with no methods A class with many methods
Not as flexible Designed to be more flexible
Can store more primitive data Not designed to store primitives, they store object references
Slightly slower than Arrays
Can only be used with an import statement

Real Life Array Example: You always have to have five players on the court

Real Life ArrayList Example: In dodgeball, the number of people in the game is changing based on who comes in or gets out

Primitive Data Types:

  • boolean
  • char
  • double
  • int

Wrapper Class Data Types (Store the primitive values as objects)

  • Boolean
  • Character
  • Double
  • Integer
import java.util.ArrayList; //you must import the java.util package

// Instantiating: ArrayList<DataType> variableName = new ArrayList<>(n);
//DataType must be nonprimitive data type

public class introArrayList {
    public static void main (String[] args) {
        ArrayList<Integer> e1 = new ArrayList<Integer>(); //empty
        ArrayList<String> e2 = new ArrayList<String>(5); //5 elements
        ArrayList<Dogs> e3 = new ArrayList<Dogs>(); //you can store whatever objects you want
    }
}

7.2 ArrayList Methods

There are a lot of cool methods that you can use with arrayLists, but here are the ones College Board wants you to know for 7.2:

size();

  • Returns the number of elements in the list

add(obj);

  • Adds element at the end

add(index, object);

  • Adds element at specific index

remove(index);

  • Removes element from specific index

set(index, object);

  • Replaces element at index with new object

get(index);

  • Returns element at index
import java.util.ArrayList; 

public class methodsArrayList {
    public static void main (String[] args) {
        ArrayList<String> dogs = new ArrayList<String>(Arrays.asList("Sparky", "Duke", "Noodle"));
        ArrayList<String> dogs2 = new ArrayList<>(Arrays.asList("Sparky", "Duke", "Noodle"));
        System.out.println("There are " + dogs.size() + " in the ArrayList"); 
        System.out.println("There are " + dogs2.size() + " in the ArrayList");
        
        //objects you add must be of the same data type
        dogs.add("Peanut");
        System.out.println("There are now " + dogs.size() + " dogs in the ArrayList"); 

        String myDog = dogs.get(2);
        System.out.println("My dog is named " + myDog);
    }
}

//Note: you don't need to declare <String> again after new ArrayList

methodsArrayList.main(null);
There are 3 in the ArrayList
There are 3 in the ArrayList
There are now 4 dogs in the ArrayList
My dog is named Noodle
//Hmmmm... seems suspect

import java.util.ArrayList; 

public class example {
    public static void main (String[] args) {
        ArrayList<Boolean> questions = new ArrayList<>();
        questions.add(true);
        questions.add(false);
        myMethod(questions);
    }
    public static void myMethod(ArrayList arr)
    {
        if (arr.size()>0)
        {
            arr.set(0,"Hello"); //String with boolean??? Uh oh!
            System.out.println(arr.get(0));

        }
    }
}

example.main(null);
Hello
import java.util.ArrayList; 

public class example {
    public static void main (String[] args) {
        ArrayList<Boolean> questions = new ArrayList<>();
        questions.add(true);
        questions.add(false);
        myMethod(questions);
    }
    public static void myMethod(ArrayList<Boolean> arr)
    {
        if (arr.size()>0)
        {
            arr.set(0,"Hello"); //String with boolean??? Uh oh!
            System.out.println(arr.get(0));

        }
    }
}

example.main(null);

//Make sure to specify data type so the compiler is more helpful and it avoids confusion
//This also applies for returning and arrayList as well
|               arr.set(0,"Hello"); //String with boolean??? Uh oh!
incompatible types: java.lang.String cannot be converted to java.lang.Boolean
//Returning an ArrayList

public static ArrayList methodName (ArrayList arr){
    return arr;
}
// HACK!!!!
// Create an arrayList and use one of the cool methods for it

import java.util.ArrayList; 

public class hack1 {
    public static void main (String[] args) {
       ArrayList<Integer> numbers = new ArrayList<Integer>();
       numbers.add(1);
       numbers.add(2);
       numbers.add(3);
       for (int number : numbers) {
        System.out.println(number * 2);
       }
    }
}

hack1.main(null);
2
4
6

7.3 Traversing ArrayLists

  • there are 2 ways to traverse arraylists: for loops and enhanced for loops
  • use get() instead of bracket notation for getting an element of an arraylist
  • use size() to find number of elements in arraylist instead of using .length

for loop

import java.util.*;
 
public class main {
   
    public static void main(String[] args) {
        
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
 
        for (int i = 0; i < numbers.size(); i++) {
            System.out.print(numbers.get(i) + " ");    
        }       
    }
}
  
main.main(null);
1 2 3 4 5 

enhance for loops

import java.util.*;
 
public class main {
   
    public static void main(String[] args) {
        
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
 
        for ( int num : numbers ) 
        System.out.print(num + " ");     
    }
}
  
main.main(null);
1 2 3 4 5 

Common Mistakes

  • don't forget to import java.util.ArrayList
  • don't declare or instantiate ArrayList with a primitive data type, which are things such as int, double, and booleans.
  • don't forget the parentheses at the end of the constructor and the element types with the brackets: ArrayList list = new ArrayList(); </li>
  • don't confuse arrays with arraylists, don't use [], don't use .length use .size() instead
  • </ul> </div> </div> </div>

    Hack #2

    import java.util.ArrayList;
    
    ArrayList<String> color = new ArrayList<String>(); 
    color.add("red apple");
    color.add("green box");
    color.add("blue water");
    color.add("red panda");
    
    
    /*/ 
    using 
    
    if(color.get(i).contains("red"))
    
    iterate through the arraylist and remove all elements that contain the word red in them
    /*/
    
    for (int i = 0; i < color.size(); i++) {
        if (color.get(i).contains("red")) {
            color.remove(i);
        }
    }
    
    System.out.println(color);
    
    [green box, blue water]
    

    7.4 Developing Algorithms Using ArrayLists

    Modify Array Values

    ArrayList<Integer> num = new ArrayList<Integer>(); 
    
    num.add(5);
    num.add(1);
    num.add(3);
    
    for (int i = 0; i < num.size(); i++) {
      num.set(i, num.get(i) * 2); 
    }
    System.out.print(num);
    
    [10, 2, 6]

    find max value

    ArrayList<Integer> num = new ArrayList<Integer>(); 
    
    num.add(5);
    num.add(1);
    num.add(3);
    
    int maxValue = num.get(0);
    for (int number: num) {
      if (number > maxValue) { 
        maxValue = number;
      }
    }
    
    System.out.print(maxValue);
    
    5

    find min value

    ArrayList<Integer> num = new ArrayList<Integer>(); 
    
    num.add(5);
    num.add(1);
    num.add(3);
    
    int minValue = num.get(0);
    for (int number: num) {
      if (number < minValue) { //if new min value found, replace current minValue
       minValue = number;
      }
    }
    System.out.print(minValue);
    
    1

    Hack #3

    // find the sum of the elements in the arraylist
    
    ArrayList<Integer> num = new ArrayList<Integer>(); 
    
    num.add(5);
    num.add(1);
    num.add(3);
    
    int sum = 0;
    
    for (int number : num)  {
        sum += number;
    }
    
    System.out.println(sum);
    
    9
    

    7.5 Searching

    • Often times we need to locate data inside linear structures. Normally we would use for loops in order to specify each element, one at a time, and do not need to track the index after execution.
    for ( int index = 0; index < items.size(); index++ ){ //forward searching
        
        if ( items.get(index) == num ){
            return index;
        }
    
    }
    

    Important Things to Keep in Mind

    • When looking at int values, the == operator should be used.
    • When searching for a double value, we need to make sure the value is close enough by doing some math.
    • Object instances should always use the .equals(otherThing) method to check for a match.

    When searching a linear structure we need to send it the structure and what we are looking for as parameters. A standard for loop with an if block is all we need to search any linear structure.

    public int whereIsMyNumber(int magicNumber, int [] myNumbers)
        {
            for (int index = 0; index < myNumbers.length; index++) //search through every single spot
            {
                if (myNumbers[index] == magicNumber) //do they match? if so return index
                {
                    return index;
                }
            }
            return -1; // if searched through every single spot, indicate its not there
        }
    
    • You shouldn't use the == operator when looking for an object. It will only return true if the variable and the element stored at the index point to the same memory, are aliases of each other.

    Here is an example of how you would search for a traditional object:

    public int findTheWord(String searchedPhrase, ArrayList<Book> myBooks)
        {
            for (int index = 0; index < myBooks.size(); index++) //search through every book in structure
            {
                Book currentBook = myBooks.get(index); //hold current book with current book variable
                String currentPhrase = currentBook.getDescription(); //get description of current book and store in variable currentPhrase
                if (currentPhrase.equals(searchedPhrase)) //if parameter = current phrase of book looking at - using .equals instead of == operator
                {
                    return index; 
                }
            }
            return -1; //if no match found, indicate its not there
        }
    

    7.6 Sorting

    • Selection sort identifies either the maximum or minimum of the compared values and iterates over the structure checking if the item stored at the index matches the condition, if so, it will swap the value stored at the index and continue.
    • The insertion sort is characterized by building a sorted structure as it proceeds. It inserts each value it finds at the appropriate location in the data structure. This is often accomplished by using a while loop as the inner loop.
    for (int outer = 1; outer < randomList.size(); outer++)
    {
        DebugDuck tested = randomList.get(outer); //extract out a value out of list, passes to outer
        int inner = outer - 1;      //goes back and compares to previous
    
        while ( inner >= 0 && tested.compareTo(randomList.get(inner)) < 0 ) //checks to see if index is valid
        {
            randomList.set(inner + 1, randomList.get(inner)); //move up by one and replace original location
            inner--;
        }
        randomList.set(inner + 1, tested); //anything taken out would be placed back into structure
    }
    

    7.7 Ethical Issues Around Data Collection

    Safety with Data Collection

    It is very important to minimize user data collection in our programs. While collecting data in a smaller program may not be a big issue, establishing good practices with data security is always a safer bet when eventually moving to larger projects that manage data.

    Whenever you come across data that you no longer will need, it is a good practice to explicitly remove that data altogether.

    import java.util.Scanner;
    import java.util.Arrays;
    
    public class dataRemoval {
    
        public static void main(String[] args) {
    
            // just a scanner object
            Scanner sc = new Scanner(System.in);
    
            // makes an arraylist with some users already in it
            ArrayList<String> userList = new ArrayList<>(Arrays.asList("Kian", "Kiannp44@gmail.com", "Samuel", "samuelwaang@gmail.com", "Calissa", "calissaT@gmail.com"));
    
            // takes user's name
            System.out.println("Log in ---");
            System.out.println("Please enter your name:");
            String name = sc.nextLine();
            System.out.println(name);
            userList.add(name);
    
            // takes user's email
            System.out.println("Please enter your email:");
            String email = sc.nextLine();
            System.out.println(email);
            userList.add(email);
    
            // prints all the current users in arraylist
            System.out.println();
            System.out.println("Current users in databse ---");
            System.out.println(userList);
    
            // prompt to log out
            System.out.println();
            System.out.println("Would you like to log out? (y/n)");
            String logOut = sc.nextLine();
            if (logOut.equals("y")) { // if user logs out, remove their name and email from arraylist
                System.out.println(logOut);
                userList.remove(name);
                userList.remove(email);
    
            }
    
            // reprints current users in arraylist
            System.out.println();
            System.out.println("Current users in database ---");
            System.out.println(userList);
        }
    }
    
    dataRemoval.main(null);
    
    Log in ---
    Please enter your name:
    Evan
    Please enter your email:
    evanjoelsanchez@gmail.com
    
    Current users in databse ---
    [Kian, Kiannp44@gmail.com, Samuel, samuelwaang@gmail.com, Calissa, calissaT@gmail.com, Evan, evanjoelsanchez@gmail.com]
    
    Would you like to log out? (y/n)
    y
    
    Current users in database ---
    [Kian, Kiannp44@gmail.com, Samuel, samuelwaang@gmail.com, Calissa, calissaT@gmail.com]
    

    Anonymizing Personal Data

    Instead of using names for users, we can use hash codes instead, which means that each user will simply be identified by their hash code.

    public class hashUsers {
    
        public static void main(String[] args) {
    
            Scanner sc = new Scanner(System.in);
    
            String name = sc.nextLine();
    
            // this .hashCode() method will convert the name to a code which cannot be traced back to that original name
            int id = name.hashCode();
            
            name = null; // name is now null, and nobody will ever know the original name I put in
    
            System.out.println("Hash Code: " + id);
        }
    }
    
    hashUsers.main(null);
    
    Hash Code: 2172094
    

    The Takeaway

    It is important to understand that as a programmer handling user data, it is your responsibility to protect that collected data. The less data you collect, the less you have to safeguard. A compromised database will generally be an expensive lawsuit in a large scale project.

    Homework

    Quizizz

    Results

    </div>