Learning Objectives:
-
With an Arraylist you can traverse objects using a for or while loop.
-
Traversing objects is similar to iterating through objects.
Essential Knowledge:
-
Iteration statements can be used to accsess all the elements in an Arraylist. This is called traversing the Arraylist.
-
Deleting elements during a traversal of an Arraylist requires special techniques to avoid skiping elements. This is called traversing the Arraylist.
-
The indicies of an Arraylist start at 0; If you try to use any value lower than 0, you will get an ArrayIndexOutOfBoundsException error
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArrayList<String> roster = new ArrayList<>();
roster.add("Hello");
roster.add("World");
roster.add("Java");
int sum = 0;
for (int i = 0; i < roster.size(); i++) {
String element = roster.get(i);
if (element != null) {
sum += element.length();
}
}
System.out.println(sum);
}
}
Breakdown:
-
We are first declaring a new arraylist and adding a few elements.
-
Next, we set the “sum” variable as 0.
-
We set a for loop to traverse through the arraylist, iterating through all the indices in the arraylist and adding up the lengths of all the values.
-
Lastly, we print it out.
Loop Conditions:
- There are a few diffrent loop conditions you can use to traverse an Arraylist:
First, there are three major parts of a for loop: Initialisation, in which you declare the index, can be modified to change where you want to traverse from.
Boolean condition, in which you declare the stop condition, can be modified in order to change the index you want to stop traversing in.
Update, in which you declare how many indexes to go through, can be modified to skip certain indicies and traverse in a certain direction.
Practice:
Suppose we have an arraylist named grades, and we want to remove the entries that are lower than 70. replace the question marks with code to solve the problem:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArrayList<int> grades = new ArrayList<>();
grades.add(68.9);
grades.add(71);
grades.add(100);
grades.add(80);
for(int i = 0; i<???; i???){
if(grades.get(i)<70){
???
}
}
System.out.println(grades);
}
}
Using Enhanced For-Loop With Traversing:
-
Using Enhanced for loop is easier to read and write and is also more concise and avoids errors.
-
Indexes are not explicitly used and copies of the current element are made at each iteration.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> roster = new ArrayList<>();
roster.add("Hello");
roster.add("World");
roster.add("Java");
// Using an enhanced for loop to iterate through the ArrayList
for (String element : roster) {
System.out.println(element);
}
}
}
Common mistakes:
-
Using the Wrong Data Type: Ensure that you declare your ArrayList with the correct data type. Using the wrong data type can lead to type mismatches and errors.
-
Incorrect Indexing: Be cautious when using a standard for loop. Off-by-one errors or accessing elements that don’t exist can lead to runtime exceptions.
-
Modifying the List During Iteration: Modifying an ArrayList (adding or removing elements) while iterating over it can lead to a ConcurrentModificationException. To avoid this, use an Iterator or create a copy of the list if modifications are needed.
-
Not Checking for Null Elements: When using enhanced for loops or iterators, check for null elements if there’s a possibility that your list contains them to avoid NullPointerExceptions.
-
Inefficient Searching: If you need to find a specific element, avoid using a linear search within a loop. Use appropriate methods like contains() or indexOf() to find elements efficiently.
Hax:
- Create a scenario which requires the use of arraylist traversal and create code to solve it.
- Extra points to creative scenarios
- 90% credit to any working code and scenario
- 80% credit to incomplete code if you provide explanation of it
- -10% deduction for late submition