Arrays and Arraylists Flashcards
What is the major difference between arrays and ArrayLists?
ArrayLists are dynamic and we do not have to specify the size while creating it. Arrays are created with a set immutable size.
What Java package is the ArrayList a part of?
java.util
What is the syntax to import an ArrayList?
import jave.util.ArrayList;
What is the syntax to create an array of double of the size 5 named score?
double[] score = new double[5];
What is the syntax to create an array of Strings named flavor with the data “Chocolate”, “Strawberry”, “Vanilla”?
String[] flavor = {“Chocolate”, “Strawberry”, “Vanilla”};
What is the syntax to create an ArrayList of data type Double of the size 5 named score?
ArrayList<Double> score = new ArrayList<>(5);
Note that the initial capacity is optional, but it can improve performance if you know the size of the ArrayList in advance.</Double>
What is the syntax to create an ArrayList of Strings named flavor with the data “Chocolate”, “Strawberry”, “Vanilla”?
ArrayList<String> flavor = new ArrayList<>();
flavor.add("Chocolate");
flavor.add("Strawberry");
flavor.add("Vanilla");</String>
What is the syntax to print out the values of a one dimensional array named flavor to the output console?
This will print the array like [xxx,xxx,xxx]
System.out.println(Arrays.toString(flavor));
These next two will print out each array item on it’s own line:
Arrays.stream(flavors).forEach(System.out::println);
for (String favor : flavors) {
System.out.println(flavor);
}
What is the syntax to print out the values of an ArrayList named flavor to the output console?
This will print the ArrayListlike [xxx,xxx,xxx]
System.out.println(Arrays.toString(flavor));
These next two will print out each ArrayList item on it’s own line:
for(String f : flavor) {
System.out.println(f);
}
Or
flavor.forEach(System.out::println);
What is the syntax to print out the values of a two dimensional array named flavor to the output console?
This will print out [[xxx,xxx],[xxx,xxx],[xxx,xxx]]
(notice the strings aren’t enclosed in “”)
System.out.println(Arrays.deepToString(flavor));
What is the syntax to remove the 3rd element in an ArrayList named flavor?
flavor.remove(3);
What is the syntax to add “Peppermint” to the end of an ArrayList named flavor?
flavor.add(“Peppermint”);
Can an ArrayList use primative data types?
No. We need to use the corresponding wrapper classes.
What is the class we need to import in order to declare a ArrayList with an array and what is the import syntax?
import java.util.Arrays;
What is the syntax to create an ArrayList of Strings named flavor with the data “Chocolate”, “Strawberry”, “Vanilla” using an ArrayList constructor? Include the import statements.
import java.util.ArrayList;
import java.util.Arrays;
ArrayList<String> flavor = new ArrayList<>(
Arrays.asList("Chocolate", "Strawberry", "Vanilla")
);</String>