Skip to content

ArrayList

Sharina Stubbs edited this page Sep 19, 2019 · 3 revisions
  • Can hold whatever type of data you want, you must specify what the array list is of, using angle bracket syntax.
  • Ultimately have to specify the arraylist type twice,with type parameter in angle brackets and again with just the diamond of angle brackets on the right.

Pros

  • Holds things in order
  • Allows for adding or removing pieces of data - a mutable data type
  • Can add things to a particular index, with built in functionality
  • .add puts things at the end.
  • Can remove things at a particular index, with .remove

Cons

  • Cannot hold primitive values...
  • ... have to use the wrapper class. So, we create

Examples

Example with for loop

package demo;

public class Library {
    public boolean someLibraryMethod() {
        ArrayList<String> names = new ArrayList<>();
        names.add("Razzle");
        names.add("Luna");
        names.add("Mabel");
        for(int i = 0; i < names.size(); i++) {
            System.out.println(names.get(i));
        }
        return true;
    }
}

Example with for each loop

public class Library {
    public boolean someLibraryMethod() {
        ArrayList<String> names = new ArrayList<>();
        names.add("Razzle");
        names.add("Luna");
        System.out.println(names.remove( index:1)); <----- this will print out the value at index1
        names.remove (index: 1);
        for(String name : names) {
            System.out.println(name);
        }
        // to take care of primitives must use wrapper class that you can access with IDE.
        ArrayList<Integer> nums = new ArrayList<>();
        nums.add(4);
        int num = nums.remove( index:0);
        return true;
    }
}

Sample Code

Code Fellows lecture demo code:

https://github.com/codefellows/seattle-java-401d6/blob/master/class-03/demo/src/main/java/demo/Library.java

Clone this wiki locally