I'm studying OOP, and I came across array lists. I'd like to know how the remove() function actually works, and what is the most efficient way to use it.
First method to delete all the "BB"
public class ArrayListTest {
public static void main(String args[]){
ArrayList<String> Alist = new ArrayList<String>();
Alist.add("AA");
Alist.add("BB");
Alist.add("AA");
Alist.add("AA");
Alist.add("AA");
Alist.add("BB");
System.out.println("Original ArrayList : " + Alist);
int n = 0 ;
for (int i = 0; i < Alist.size(); i++){
n++;
Alist.remove("BB");
}
System.out.println(n);
System.out.println("Modified ArrayList : " + Alist);
}
}
The output
run:
Original ArrayList : [AA, BB, AA, AA, AA, BB]
4
Modified ArrayList : [AA, AA, AA, AA]
BUILD SUCCESSFUL (total time: 0 seconds)
Secend Method to delete all the "BB"
public class ArrayListTest {
public static void main(String args[]){
ArrayList<String> Alist = new ArrayList<String>();
Alist.add("AA");
Alist.add("BB");
Alist.add("AA");
Alist.add("AA");
Alist.add("AA");
Alist.add("BB");
System.out.println("Original ArrayList : " + Alist);
int n = 0 ;
while(Alist.contains("BB")){
n++;
Alist.remove("BB");
}
System.out.println(n);
System.out.println("Modified ArrayList : " + Alist);
}
}
The output
run:
Original ArrayList : [AA, BB, AA, AA, AA, BB]
2
Modified ArrayList : [AA, AA, AA, AA]
BUILD SUCCESSFUL (total time: 0 seconds)
It's confusing because the counter was triggered to increase a few more times in the first one, but is it actually more efficient, or is the "contains()" looping through the whole array list at each check on the statement behind the scene.