ch11_arraylist.docx - inCS 1302 \u2013 Chapter 11 The ArrayList Class Section 11.12 \u2013 The ArrayList Class 1 An ArrayList is like an array in that it is

ch11_arraylist.docx - inCS 1302 u2013 Chapter 11 The...

This preview shows page 1 - 3 out of 12 pages.

inCS 1302 – Chapter 11 The ArrayList Class Section 11.12 – The ArrayList Class 1. An ArrayList is like an array in that it is used to store objects. However, it also has useful methods to manipulate the objects. Some of the major methods are shown in the diagram on the right. ArrayList is defined in the java.util package and so to use it, you must import it: import java.util.ArrayList; 2. Example – Below we provide examples of most of the methods above. a. We can create an ArrayList to hold integers with this statement: ArrayList<Integer> ints = new ArrayList<>(); Note the following: We must specify what type of objects we will store in an ArrayList . The <…> construct is something new. This is referred to as generics which we discuss more fully in another chapter. For now, the “Integer” inside the angle brackets is the generic type and specifies what type of data the ArrayList will hold. The generic type cannot be a primitive type, it must be a full-fledged class. In this case we use the Integer wrapper class to define an ArrayList to hold ints. We don’t have to specify how many items the ArrayList can hold as we do with an array. It will hold as many items as the memory on your computer will allow. b. The ArrayList class has an add(obj) method to add objects to the end of the list. For example: ints .add(47); ints .add(91); ints .add(16); Internally, an ArrayList uses an array to hold the objects. Thus, after the three statements above, we can think of it looking like this: 0 1 2 3 4 5 6 7 8 9 10 47 91 16 Thus, 47 is stored at index=0, 91 is stored at index=1, and 16 is stored at index=2 c. The ArrayList class has a size method that returns the number of objects in the list. For example: int size = ints .size(); Thus, size=3 in the example. Note that there are no “holes” in an ArrayList . In other words, there are always elements in positions 0 through size()-1. 1
Image of page 1
. ); For
Image of page 2
Image of page 3

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture