unit 7 Flashcards
What is an ArrayList in Java?
A resizable array-like structure from java.util package.
How do you import ArrayList?
import java.util.ArrayList;
How do you declare an ArrayList of Strings?
ArrayList<String> list = new ArrayList<>();</String>
How do you add an element to an ArrayList?
list.add(“item”);
How do you access an element in an ArrayList?
list.get(index)
How do you change an element in an ArrayList?
list.set(index
How do you remove an element from an ArrayList?
list.remove(index)
How do you find the size of an ArrayList?
list.size()
What happens if you access an invalid index in an ArrayList?
IndexOutOfBoundsException
What type of data can ArrayLists store?
Objects (not primitives directly)
What wrapper class is used for int in ArrayLists?
Integer
What wrapper class is used for double in ArrayLists?
Double
Can ArrayLists store primitive types?
No
What is auto-boxing?
Automatic conversion between primitives and wrapper classes.
What is unboxing?
Automatic conversion from wrapper classes back to primitives.
How do you traverse an ArrayList using a for loop?
for (int i = 0; i < list.size(); i++) { list.get(i); }
How do you traverse an ArrayList using an enhanced for loop?
for (String s : list) { System.out.println(s); }
Can you modify elements while using enhanced for loop?
No
How do you find if an ArrayList contains an item?
list.contains(item)
How do you find the index of an item in an ArrayList?
list.indexOf(item)
What does list.indexOf(item) return if item is not found?
-1
How do you remove an item by value?
list.remove(new Integer(value)) or list.remove(“string”)
What happens when you remove an item from an ArrayList?
Elements shift left and size decreases.
How can you copy one ArrayList into another?
Use a loop or the constructor: new ArrayList<>(oldList);