Module 07: ArrayList Flashcards
7.1 ArrayList
What is an ArrayList?
Mutable list of object references
(A more convenient way to create adjustable arrays in through the ArrayList class)
7.1 ArrayList
How does an ArrayList look like?
import java.util.ArrayList;
ArrayList list = new ArrayList();
- Need import java.util.ArrayList; to use array list
- E represents the data type that is used
- declaration type must match the initialization type
- Can only store objects, so must use the Integer and Double class
- ArrayList () creates an empty ArrayList
- Dont need to specify the length of the arrayList
7.1 ArrayList
What is the difference between ArrayLists and Arrays?

7.1 ArrayList
How do you create an ArrayList of Strings?
- String[] list = new String[];
- ArrayList list = new ArrayList();
- ArrayList list = new ArrayList;
- List list = new List();
5.
2. ArrayList list = new ArrayList();
7.1 ArrayList
What is one of the primary differences between an ArrayList and an Array?
- ArrayLists have a fixed number of values, while Arrays can change in size.
- Arrays have a fixed number of values, while ArrayLists can change in size.
- Arrays are only able to store objects, while ArrayLists can store primitive and object values.
- ArrayLists are lists, while arrays are data structures.
- Arrays have a fixed number of values, while ArrayLists can change in size
7.1 ArrayList
True or False:
Attempting to add an int or double primitive value to an ArrayList will result in an error.
False
When an int or double value is added to an ArrayList, it is automatically converted to its Wrapper class, and when it is accessed, is transformed back into its primitive value.
7.2 ArrayList Methods
boolean add(E obj):
Appends obj to end of list
arrrayList.add(”Add!”)
7.2 ArrayList Methods
void add(int index, E obj):
Inserts obj at position index moves element index and higher up and adds 1 to size
- arrayList.add(2, “Add”)
- Increases index of higher values
7.2 ArrayList Methods
E get(int index)
Returns element at the position index
String elem = arrayList.get(2);
7.2 ArrayList Methods
int size()
Returns the number of elements in the list
int num = arrayList.size()
7.2 ArrayList Methods
E set(int index, E obj)
Replace elements at index with obj. Returns replaced element
arrayList.set(2, “NewValue”)
7.2 ArrayList Methods
E remove(int index)
Removes an element from position index. Substracts 1 from size and moves elements index and higher down one index.
arrayList.remove(2);
- Decreases index of value index and higher
- Can also return the value being removed
7.2 ArrayList Methods
How do the features of arrays and ArrayLists compare?

7.2 ArrayList Methods
What value will be printed in the console after this series of commands? Assume that the ArrayList package has been imported.
ArrayList array = new ArrayList();
array.add(3);
array.add(9);
array.add(10);
array.remove(1);
array.set(0, 3);
int num = array.get(1);
System.out.println(array.size());
- 1
- 2
- 3
- There will be an error caused by an incorrect use of ArrayList Methods.
- 2
7.2 ArrayList Methods
What value will be printed in the console after this series of commands? Assume that the ArrayList package has been imported.
ArrayList array = new ArrayList();
array.add(3);
array.add(9);
array.add(10);
array.remove(1);
array.set(0, 3);
int num = array.get(1);
System.out.println(num);
- 3
- 9
- 10
- 2
- 10
7.2 ArrayList Methods
What value will be printed in the console after this series of commands? Assume that the ArrayList package has been imported.
ArrayList names = new ArrayList();
names.add(“Michael”);
names.add(“Lebron”);
names.add(“Serena”);
names.add(“Shaq”);
String firstName = names.remove(0);
String secondName = names.set(0, “Venus”);
names.add(2, firstName);
System.out.println(“Names:” + secondName + “ and “ + names.get(1));
- Names: Lebron and Michael
- Names: Venus and Serena
- Names: Michael and Shaq
- Names: Lebron and Serena
- This will cause an error, as names.remove cannot be assigned to a value.
- Names: Lebron and Serena
7.3 Traversing ArrayList
How do you traverse an ArrayList?
ArrayList scores = new ArrayLists();
for(int i = 0; i < scores.size(); i++)
{
//This prints out the ith element System.out.println(scores.get(i));
}
- i iterates from 0 to size()
- Each iteration of i accesses the index of scores at index i
7.3 Traversing ArrayList
How do you traverse an ArrayList using a while loop?
int i = 0;
while(i < scores.size())
{
System.out.println(scores.get(i)); i ++;
}
7.3 Traversing ArrayList
How do you traverse an ArrayList using an enhance loop?
for(int score: scores)
{
System.out.printlnt(score);
}
7.3 Traversing ArrayList
How do you remove an element from the array?
public void removeA(ArrayList list)
{
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).startsWith(“A”))
{
list.remove(i);
i–;
}
}
}
7.3 Traversing ArrayList
How do you remove elements from an ArrayList using a while loop?
int index = 0;
while(index < list.size())
{
if(list.get(index).startsWith(“A”))
{
list.remove(index);
}
else
{
index++;
}
}
7.3 Traversing ArrayList
Why should you not use enhanced for loops to remove elements from an ArrayList?
Trying to remove() with an enhanced for loop will often result in a ConcurrentModificationException
Error occurs when objects are being modified while they are being iterated on
Generally speaking, we should not iterate with enhanced for loops when adding or removing items
7.3 Traversing ArrayList
True or False: Enhanced for loops should not be used to traverse ArrayLists.
False
7.3 Traversing ArrayList
Will this method correctly traverse an ArrayList and remove all multiples of 3?
public void remove3s(ArrayList array)
{
int counter = 0;
while(counter < array.size())
{
if(array.get(counter) %3 == 0)
{
array.remove(counter);
counter++;
}
else
{
counter++;
}
}
}
- Yes, this method is written correctly, and will remove all multiples of 3 in an ArrayList.
- No, this method is not written correctly, as the counter in the if statement will skip the next value, as the values will shift down in the ArrayList.
- No, this method is not written correctly, as the counter in the else statement will skip the next value, as the values will shift down in the ArrayList.
- No, this method will not work because the methods used to access the ArrayList are incorrect.
- No, this method is not written correctly, as the counter in the if statement will skip the next value, as the values will shift down in the ArrayList
7.4 Developing Algorithms
What is the structure to insert elements into an array?

7.4 Developing Algorithms
Transverse an ArrayList to add number + 2 after an odd element in the ArrayList:


7.4 Developing Algorithms
What are common ArrayList Algorithms
- Determine a min or max value
- Compute a sum, average, or mode
- Determine if at least 1 element has a particular property
- Determine if all elements have a particular property
- Access all consecutive Paris of elements
- Determine the presence or absence of duplicate elements
- Determine the number of elements meeting specific criteria
- Shifts or rotates elements
- Reverse the order of arrays
7.4 Developing Algorithms
How to you shift, rotate, or reverse elements in an ArrayList?

7.4 Developing Algorithms
How do you transverse an ArrayList to add two ArrayList variables?

7.5 Searching
Which of these method implementations would correctly insert an element into an ArrayList before every even index?
(1)
public void addEven(ArrayList array, E element)
{
for(int index = 0; index < array.size(); index++)
{
if(index %2 == 0)
{
array.add(index, element);
index++;
index++;
} } }
(2)
public void addEven(ArrayList array, E element)
{
for(int index = 0; index < array.size(); index++)
{
if(index %2 == 0)
{
array.add(index -1, element);
index++;
} } }
(3)
public void addEven(ArrayList array, E element)
{
for(int index = 0; index < array.size(); index++)
{
if(index %2 == 0)
{
array.add(index, element);
index++;
} } }
(3)
public void addEven(ArrayList array, E element)
{
for(int index = 0; index < array.size(); index++)
{
if(index %2 == 0)
{
array.add(index, element);
index++;
} } }
7.5 Searching
What is Linear Searching?
- How: Given a list and element to search for, return the index of that element in the list
- if the element does not exist = return -1
- Called Linear or Sequential search
Checks each element in order until the desired value or end of the array is reached
7.5 Searching
What is the structure of Linear Searching?

7.5 Searching
What are the pros and cons of linear searching?
Pros:
Linear Search is fairly easy to implement and understand
Cons:
As the size of the data increase; however, the longer Linear Search takes to complete
7.5 Searching
True or False: Linear Search becomes more efficient as more values are added to a particular data set.
False
7.5 Searching
How does Linear Search work?
- Linear Search traverses an array until the desired value is found, or until the end of the array.
- Linear Search traverses an array from the last value to the first value until the desired value is found.
- Linear Search uses a while loop to traverse an array for the desired value, or until the end of the array.
- Linear Search searches for desired values by searching the the next highest value in an array, and seeing if that is the desired value.
- Linear Search traverses an array until the desired value is found, or until the end of the array
7.6 Sorting
What is sorting and its purpose?
How many types are there?
- Data sets grow, they can be harder to manage and sort through!
- When data is disorganized, it can be hard to find values easily - sorting makes it easier to manage
Sorting Algorithms:
Types: (1) Selection Sort and (2) Insertion Sort
7.6 Sorting
What are selection sorting and its steps?
Sorts an array by repeatedly finding the minimum value, and moving it to the front of the array
Steps:
- Pick current index
- Find minimum in the rest of the line
- Swap to put the minimum in the correct position
7.6 Sorting
Pseudocode for Selection Sort
- traverse each index up to the second to the last element
- Find the minimum in the rest of the line
- set the current index to minimum
- traverse from current index to end of list
- if index < current index, index is minimum
- Find the minimum in the rest of the line
- Swap the index and minIndex
- Create temporary variable to store current index value
- Make current index value that minIndex value
- Make minIndex value the temporary variable value
7.6 Sorting
What is the structure for selection sorting?

7.6 Sorting
How many comparisons will the selection sort algorithm make on an array of 8 elements?
28
= 7 + 6 + 5 + 4 + 3 + 2 + 1
7.6 Sorting
How does Selection Sort work to sort an array?
- Selection Sort swaps the first value of an array with the last index of an array, then swaps the second value in an array with the second to last value, until all values have swapped places.
- Selection Sort iterates through each index and swaps the current index with the minimum value that exists in the indices greater than the current index.
- Selection Sort sets the first index as sorted, and shifts each minimum value into the correct position by finding the lowest value on the sorted side of the array at indices lower than the current index.
- Selection Sort finds the lowest value in an array and shifts all elements to the right of that value.
- Selection Sort iterates through each index and swaps the current index with the minimum value that exists in the indices greater than the current index
7.6 Sorting
What is Insertion Sort?
Sorts an array by sorting each element compared to the element already sorted to their left
7.6 Sorting
What is the steps for Insertion Sort?
- Mark first element as sorted
- Choose the next unsorted element
- Shift unsorted element into the correct position in sorted part of the list
- Now left part of list is sorted
- Choose the next unsorted element
- Shift unsorted element into correct position in sorted part of list

7.6 Sorting
What is the pseudocode for selection sort?
- Traverse each element starting from index 1
- Traverse sorted elements to find current element position
- Shift sorted elements to place current element
7.6 Sorting
What is the structure for Insertion Sort?

7.6 Sorting
What is the difference between Insertion vs. Selection Sort and when should you use each?
The efficiency of both depends on how sorted the list order is at the start
Use Statement Execution Count can be used to compare the efficiency of sorting algorithms
array1: {0, 1, 2, 4, 3}
- When the list is almost sorted, Insertion Sort has a lower execution count than Selection short - because the while loop doesn’t execute
array2: {4, 3, 2, 1, 0}
- When the list is in reversed order, Selection Sort has a lower execution count because it only needs to swap two values, while Insertion Sort has to shift every single value
7.6 Sorting
When is it more appropriate to use Insertion Sort than Selection Sort?
- When the array is in reverse order.
- There is no difference in the speed of either sorting method.
- When the array is already slightly sorted.
- Selection sort is always faster than Insertion sort.
- When the array is already slightly sorted
7.6 Sorting
How does insertion sort work to sort an array?
- Insertion Sort finds the lowest value in an array and shifts all elements to the right of that value.
- Insertion Sort iterates through each index and swaps the current index with the minimum value that exists in the indices greater than the current index.
- Insertion Sort sets the first index as sorted, and shifts each subsequent value into the correct position by finding the lowest value on the sorted side of the array at indices lower than the current index.
- Insertion Sort swaps the first value of an array with the last index of an array, then swaps the second value in an array with the second to last value, until all values have swapped places.
- Insertion Sort sets the first index as sorted, and shifts each subsequent value into the correct position by finding the lowest value on the sorted side of the array at indices lower than the current index
7.6 Sorting
The following array is to be sorted biggest to smallest using insertion sort.
[10, 40, 50, 30, 20, 60]
What will the array look like after the third pass of the for loop?
- [60, 50, 40, 30, 20, 10]
- [50, 40, 10, 30, 20, 60]
- [50, 40, 30, 10, 20, 60]
- [60, 50, 40, 30, 10, 20]
- [10, 30, 40, 50, 20, 60]
- [50, 40, 30, 10, 20, 60]
7.7 Ethical Issues Around Data Collections
What is privacy?
Privacy is the “right to be free from unwarranted intrustion and keep certain matters from public view”
7.7 Ethical Issues Around Data Collections
What is security (and cybersecurity)?
🖇️ Security is the state of being free from danger or threat
Cybersecurity:
- 2017 Median Pay: $95,510
- Bachelor’s degree
- Job outlook (2016-26): 28% growth (much higher than average)
7.7 Ethical Issues Around Data Collections
What is your digital footprint?
Information about particular person that exists on the Internal as a result of their online activity
- Email you send
- Comments you leave
- Pictures you post
- Topics you search
- Apps you use
Builds as you use the internet
7.7 Ethical Issues Around Data Collections
How can you protect personal data?
- Use privacy settings to limit exposure
- Review posts you are tagged in
- Permanently delete old social media accounts you don’t use
- Google yourself on a regular basis
- Strong password
- Stay on secure sites with https://
- Not just http://
- The “s” is for Secure
- Monitor your webcam and microphone use
- Be aware of your location sharing
- Know site privacy policies when you agree to them
- Avoid phishing attempts in emails
- Be careful logging into public computers
- Stay up to date on best web security practices
- If you think you’re being violated - contact parent/gaurdian, company owns the sire/app, and school or IT person
7.7 Ethical Issues Around Data Collections
What are protocols?
🖇️ Protocols for data sharing on the internet define rules and conventions for communication between network devices
- Internet is a packet-switched system through which digital data is sent by breaking the data into blocks of bits called packets
- Packets contain both data being transmitted and control information (Metadata) that helps route the data
- It is only able to work because all machines have agreed to use the same protocols for creating and reading packets
7.7 Ethical Issues Around Data Collections
What is the impact of the internet?
- Collaboration
- Communication
- Dissemination of information
- Crowdsourcing
- Anonymity
- Censorship
- Concerns over privacy and security
7.7 Ethical Issues Around Data Collections
What are the benefits of sharing data?
- Communication - Email, Video calls, Social media
- Collaborative problem solving
- E-commerce or online shopping
- Access to information
- Open databases for scientific publications
- Online learning
- GPS
- Entertainment
7.7 Ethical Issues Around Data Collections
What are the harmful effects of shared data?
- Access to information (Wikileaks)
- Several legal and ethical concerns arise from sharing data
- Access to copyrighted material
- Peer networks allow people to share content (though others would not want it to be shared)
- Easier than ever to distribute information or content that is not your own
- Anonymity:
- How identifiable internet users should be
- Equiality on the internet
- Cyberbulling
- Censorship:
- Should google display search results that have explicit or illegal content?
- Should government be able to filer what content citizens see?
7.7 Ethical Issues Around Data Collections
What is the ethical code and the Code of Ethics?
Responsibility to make sure programs and applications are ethical, legal, and socially acceptable
Code of Ethical:
Contribute to society’s well-being
Avoid harm
Honest and trustworthy
Be fair and take action to not discriminate
Respect the work required to produce new ideas, inventions, creative works, and computing artifacts
Respects privacy
Honor confidentially
7.7 Ethical Issues Around Data Collections
Which of the following are some good ways to protect your own personal data?
I. Use privacy settings to limit exposure
II. Review posts you are tagged in and take action if needed
III. Permanently delete old social media accounts you don’t use
IV. Google yourself on a regular basis
V. Use strong passwords
Vi. Stay on sites with http://
- I, II, and III
- I-V all
- IV, V, and VI
- I- VI all
2. I-V all
7.7 Ethical Issues Around Data Collections
Some good and practical ways to avoid a phishing attempt are to
I. Not click through any links in an email that seem suspicious
II. Not download any attachments in an email that seem suspicious
III. Not use email services at all
IV. Consider the source of each email
V. Consider if the email contents sound too good to be true, like you have won a prize or something
- I and II
- IV and V
- I - V all
- I, II, IV and V
- I, II, IV and V
7.7 Ethical Issues Around Data Collections
Protocols for data sharing on the internet are
- rules and conventions for communication between network devices.
- ways to avoid email phishing attempts.
- ideas for establishing a positive digital footprint.
- are now considered obsolete with technologies like Web 2.0 and HTML5.
- rules and conventions for communication between network devices
7.7 Ethical Issues Around Data Collections
A field of computer science that’s related to keeping data private and secure called
- The CIA
- Computer Ethics
- Cybersecurity
- Crowdsourcing
- Cybersecurity
7.7 Ethical Issues Around Data Collections
Which of the following only has beneficial impacts on our society?
I. Collaboration
II. Communication
III. Sharing of information
IV. Anonymity
- I and II
- III
- IV
- None of these
- None of these
ArrayList Exam Quiz
Question: 1
What is the proper way to get the number of items in an ArrayList called list?
- list.length
- list.size
- list.length()
- list.size()
- list.size()
ArrayList Exam Quiz
Question: 2
What will the following code print?
ArrayList list = new ArrayList();
list.add(“Hello”);
list.add(“World”);
System.out.println(list[0]);
- “Hello”
- “World”
- “list[0]”
- There will be a compiler error
- None of the above
- There will be a compiler error
ArrayList Exam Quiz
Question: 3
What is wrong with the following code?
ArrayList list = new ArrayList();
list.add(1);
System.out.println(list.get(0));
- It will throw an IndexOutOfBoundsException.
- You cannot use int as the type in an ArrayList.
- list is a reserved word, so you can’t call the variable that.
- You need to define the new ArrayList on a new line of code.
- Nothing. The above code is correct.
- You cannot use int as the type in an ArrayList
ArrayList Exam Quiz
Question: 4
What will the following code print?
ArrayList list = new ArrayList();
list.add(0);
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
int sum = 0;
for (int i = 0; i < list.size(); i+= 2)
{
sum += list.get(i);
}
System.out.println(sum);
- 0
- 5
- 6
- 9
- 15
- 6
ArrayList Exam Quiz
Question: 5
What will the following code print?
ArrayList list = new ArrayList();
list.add(“I”);
list.add(“love”);
list.add(“coding”);
list.add(“in”);
list.add(“Java”);
list.remove(3);
System.out.println(list.get(3));
- 3
- coding
- in
- Java
- It will throw an IndexOutOfBoundsException.
- Java
ArrayList Exam Quiz
Question: 6
Consider the following statement:
ArrayList newList = /* Missing Code */
Which of the following can be replaced with /* Missing Code */ so that the statement works as intended?
I.
new ArrayList;
II.
new ArrayList();
III.
new ArrayList();
- I only
- III only
- I and III
- II and III
- I, II, and III
- II and III
ArrayList Exam Quiz
Question: 7
What would the proper initialization and declaration be for an ArrayList myTemps meant to store precise temperature measurements?
- ArrayList myTemps = new ArrayList();
- ArrayList myTemps = new ArrayList();
- ArrayList myTemps = new ArrayList();
- ArrayList myTemps = ArrayList();
- ArrayList myTemps = ArrayList();
- ArrayList myTemps = new ArrayList();
ArrayList Exam Quiz
Question: 8
Consider the following code segment:
Which of the following represents the value of nums after the code segment has been executed?
- [20, 40, 90, 50]
- [10, 20, 30, 40, 50]
- [20, 30, 90, 50]
- [20, 40, 50, 90]
- [20, 30, 80, 50]

- [20, 30, 90, 50]
ArrayList Exam Quiz
Question: 9
Consider the following code segment:
Which of the following represents the value of scales after the code has been executed?
- [SO, RE, FA, DO]
- [SO, RE, MI, FA, DO]
- [SO, RE, MI, DO]
- [FA, RE, MI, DO]
- [FA, SO, RE, MI, DO]

- [SO, RE, MI, FA, DO]
ArrayList Exam Quiz
Question: 10
Consider the following code segment:
What is printed when the code segment is executed?
- [9, 8, 7, 6, 5]
- [10, 9, 8, 7, 6]
- [9, 8, 7, 6]
- [9, 8, 7, 6, 4, 3]
- Nothing will print, as the while loop condition occurs infinitely.

- [9, 8, 7, 6]
ArrayList Exam Quiz
Question: 11
Consider the following code segment:
What is printed when the code segment is executed?
- []
- [“Two”, “Four”]
- [“Two”, “Four”, “Six”]
- [“Four”, “Five”, “Six”]
- [“Six”]

- [“Two”, “Four”, “Six”]
ArrayList Exam Quiz
Question: 12
The following method is a search method intended to return the index at which a String value occurs within an ArrayList:
However, there is currently an error preventing the method to work as intended. Which of the following Lines needs to be modified in order for the method to work as intended?
- Line 1 - The method should be returning a String value, not an int.
- Line 4 - The loop should go to < list.size() - 1 so as to avoid an IndexOutofBoundsException.
- Line 8 - The return should be the counter, not list.get(counter).
- Line 10 - As written, the counter will skip every other value.
- Line 12 - The return value should be a String, not an int.

- Line 8 - The return should be the counter, not list.get(counter).
ArrayList Exam Quiz
Question: 13
Consider the following implementation of a search method:
An ArrayList nums, is initialized with the values [1, 2, 4, 3, 4, 5]. What value would be returned from the call search(nums, 4)?
-1
2
4
This search method is written improperly, and will result in an error.
3

4
ArrayList Exam Quiz
Question: 14
Consider the following correct implementation of the selection sort algorithm:
Given an ArrayList initialized with the values [6, 5, 4, 3, 2, 1], how many times does Line 19 execute when the ArrayList is sorted using the selection sort algorithm?
6
3
5
30
4

3
ArrayList Exam Quiz
Question: 15
Consider the following correct implementation of the selection sort algorithm:
What would be the most effective way to alter this selection sort algorithm so that an ArrayList would be sorted from greatest to smallest value?
- Change Line 3 to int currentMaxIndex;
- Change Line 5 to for(int i= arr.size() -1; i > 0; i –)
- Change Line 10 to if(arr.get(j) > arr.get(currentMinIndex))
- Change Line 16 to if (i > currentMinIndex)
- Change Line 19 to arr.set(arr.get(i), currentMinIndex);

- Change Line 10 to if(arr.get(j) > arr.get(currentMinIndex))
ArrayList Exam Quiz
Question: 16
Consider the following correct implementation of the insertion sort algorithm:
The following declaration and method call are made in another method in the same class as insertionSort:
int[] nums = {6, 5, 4, 3, 2, 1};
list = insertionSort(nums);
How many times is the statement on Line 13 executed as a result of the call to insertionSort?
5
30
15
16
6

15
ArrayList Exam Quiz
Question: 17
A website organizes its list of contributors in alphabetical order by last name. The website’s new manager would prefer the contributor list to be ordered in reverse alphabetical order instead. Which classic algorithm would be best suited to complete this task?
- Linear/Sequential Search
- Selection Sort
- Insertion Sort
- None of these algorithms are viable options.
- Selection Sort
ArrayList Exam Quiz
Question: 18
A company organizes all of its client database in order of the amount of money that the account is worth. When a new account is added, it is placed in the correct order in the database based on the worth of the account. Which classic algorithm would be best suited to perform this function?
- Linear/Sequential Search
- Insertion Sort
- Selection Sort
- None of these are viable options
- Insertion Sort
ArrayList Exam Quiz
Question: 19
The following segment of code is meant to remove the even numbers from an ArrayList list and print the results:
The method as written, however, is incorrect. Which ArrayList(s) list would prove that this method was written incorrectly?
I.
[1, 2, 3, 4, 5]
II.
[2, 4, 5, 6, 7]
III.
[2, 4, 6, 8, 10]
IV.
[2, 5, 6, 7, 8]
- III only
- II and IV
- II only
- I and IV
- II and III

- II and III
ArrayList Exam Quiz
Question: 20
Consider the following code segment:
What is printed as a result of this code segment?
- [10, 15, 20, 25, 30]
- [5, 15, 20, 25, 30]
- [1, 2, 3, 4, 5]
- [5, 10, 15, 20, 30]
- An IndexOutofBoundsException occurs.

- An IndexOutofBoundsException occurs