Java Classes Flashcards
(8 cards)
The difference between an Array and ArrayList
The size of an array cannot be modified (if you want to add or remove elements, you have to create a new one). While elements can be added and removed from anArrayListwhenever you want.
What is the syntax for creating an ArrayList object called cars that will store strings?
import java.util.ArrayList; // import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object</String></String>
How do you add elements to an ArrayList
use the add() method:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}</String></String>
How do you access an element in an ArrayList?
use the get() method and refer to the index number:
cars.get(0);
How do you change an element in an ArrayList?
To modify an element, use the set() method and refer to the index number:
cars.set(0, “Opel”);
How do you remove an element(s) from an ArrayList?
To remove an element, use the remove() method and refer to the index number:
cars.remove(0);
To remove all the elements in the ArrayList, use the clear() method:
cars.clear();
How do you find the length of an ArrayList?
To find out how many elements an ArrayList have, use the size method:
cars.size();
Loop Through an ArrayList
Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run:
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}
You can also loop through an ArrayList with the for-each loop:
for (String i : cars) {
System.out.println(i);