Compare the use of ArrayLists and arrays in terms of their ability to store null values.
Both ArrayLists and arrays can store null values.
Compare the suitability of ArrayLists and arrays for scenarios where the size of the data collection is known in advance and will not change.
Arrays are more suitable in this scenario due to their lower memory overhead and potentially faster access times.
Identify the error in the following code:
ArrayList list = new ArrayList();
list.add(5);
list.add("hello");
The ArrayList is not generic, so it can hold different types. However, this is generally bad practice, and can lead to runtime errors if you try to use the elements without knowing their type.
Identify the error in the following code:
ArrayList numbers = new ArrayList();
numbers.add(3.14);
Cannot add a double (3.14) to an ArrayList of Integers. Type mismatch.
What import statement is required to use ArrayLists in Java?
import java.util.ArrayList;
Identify the error in the following code:
ArrayList names = new ArrayList(10);
names.add("Alice");
names.add("Bob");
The initial capacity in the constructor does not limit the number of elements that can be added. There is no error here.
What is wrong with the following code?
ArrayList numbers = new ArrayList();
ArrayLists cannot store primitive types directly. You must use the wrapper class 'Integer' instead of 'int'.
What is the output of the following code?
ArrayList list = new ArrayList<>();
list.add("apple");
list.add("banana");
System.out.println(list.size());
2
What is the error in the following code?
ArrayList numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
String s = numbers.get(0);
Cannot assign an Integer to a String variable. Type mismatch.
What is the output of the following code?
ArrayList flags = new ArrayList<>();
System.out.println(flags.size());
0
What is wrong with the following code?
ArrayList values = new ArrayList<>();
values.add(10);
values.add(new Integer(20));
While technically the second add will work due to autoboxing, it's bad practice to add an Integer object to an ArrayList of Doubles.
What is the output of the following code?
ArrayList words = new ArrayList<>();
words.add("hello");
words.add("world");
words.clear();
System.out.println(words.size());