![]() |
7.1 Introduction to ArrayList | 7.2 ArrayList Methods | 7.3 Traversing ArrayLists | 7.4 Developing Algorithms Using ArrayLists | 7.5 Searching | 7.6 Sorting | 7.7 Ethical Issues Around Data Collection |
Unit 7 ArrayLists P1
ArrayLists Lesson
7.1: ArrayList Intro
- ArrayLists are dynamic, meaning their size can grow or shrink as needed, but arrays are static in size
- Instead of creating a different size array each time, while painstakingly copying the data from the initial array to the new one, we can use ArrayLists!
Ex: You and ur beautiful wife have 8 kids and your house has 8 bedrooms…
In order to use the ArrayList class, it needs to be imported from the java util package. This can be done by writing import java.util.ArrayList; at the beginning of the code
import java.util.ArrayList;
ArrayList objects are initialized the same way as most object classes. However, the element type (String, Integer, Boolean) must be specified in the <>. Look at the example below, where the element type is String in this case.
ArrayList<String> list = new ArrayList<String>();
ArrayLists can be created without specifying a type, allowing them to hold any object type. However, its better to define the type because it allows the compiler to catch errors at compile time whcich makes the code more efficient and easier to debug. Example is below
ArrayList list = new ArrayList();
Popcorn Hack #1
Create 2 ArrayLists, 1 called studentName
and 1 called studentAge
import java.util.ArrayList;
public class ProductCatalog {
public static void main(String[] args) {
// what should go in the place of the question marks?
List<?> productNames = new ArrayList<>();
List<?> productPrices = new ArrayList<>();
}
}