Java Classes Flashcards

1
Q

The difference between an Array and ArrayList

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the syntax for creating an ArrayList object called cars that will store strings?

A

import java.util.ArrayList; // import the ArrayList class

ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object</String></String>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you add elements to an ArrayList

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you access an element in an ArrayList?

A

use the get() method and refer to the index number:
cars.get(0);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you change an element in an ArrayList?

A

To modify an element, use the set() method and refer to the index number:
cars.set(0, “Opel”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you remove an element(s) from an ArrayList?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you find the length of an ArrayList?

A

To find out how many elements an ArrayList have, use the size method:
cars.size();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Loop Through an ArrayList

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly