dataIcon

APCS-A Test Review

ArrayList Resources

module

ArrayLists are so important that we devoted this entire page to them.

Imagine an 'array' on steroids - with superpowers! That's an ArrayList. It's dynamic in that it can change its size and because it's generated via a class (ArrayList<E>) it has associated 'methods' (superpowers) that can be used to do powerful stuff!

It's like a set of modular warehouse units: each one can store one unit of 'data.' We can have as many as we like and can pop them in and out of a lineup as we need them. Each warehouse module, like an egg carton, can hold a single object, distinct from its neighbors, but it's all one big collection that can be manipulated easily.

Declaring/Constructing/Initializing ArrayLists:
  • Declaring an ArrayList:

    import java.util.ArrayList;
    . . .
    ArrayList<Integer> fibonacci;

    We have to import the module to use them and when we create one, we must declare the nature of its data using the 'angle brace' designation, with the 'Wrapper class' of the data we want to store inside it.

  • Constructing an ArrayList with 'new':

    fibonacci = new ArrayList<String>();
    ArrayList<String> vowels = new ArrayList<String>(5) // set initial capacity
    
  • Initializing an ArrayList with values:

    fibonacci.add(1);
    fibonacci.add(1);
    fibonacci.add(2);
    fibonacci.add(3);
    
  • ArrayLists have a method that calculates their size. Note that it is not an attribute like length which we see with primitive arrays:
    int numFibos = fibonacci.size(); //a method not an attribute!
    
  • See the example code where we construct ArrayLists from primitive arrays
Printing ArrayLists:
  • Using traditional SOPs - Questionable:

    System.out.println(fibonacci); // prints: [1, 1, 2, 3]
    
  • Using loops - Preferred:

    //using a for-each type loop:
    for(int f : fibonacci) System.out.println(f);
    
    //using a traditional for loop and the ArrayList member method: get
    for(int ndx = 0; ndx < fibonacci.size(); ndx++) System.out.println(fibonacci.get(ndx));
    
Beloved ArrayList Methods:
Method Example Output Usage/Comments
  • add()
  • add(ndx, Element)

Lookie! An overloaded instance method!

ArrayList<Integer> evens = new ArrayList<Integer>();
evens.add(0);
evens.add(2);
evens.add(4);
evens.add(6);
System.out.println(evens);
evens.add(2, 666);  //insert an element at ndx 2; others scoot over
System.out.println(evens);

'[0, 2, 4, 6]'
'[0, 2, 666, 4, 6]'

Make sure you add the right kind of data!

  • remove(int index)
  • remove(Object obj)

Lookie! An overloaded instance method!

//assume an aL of lc vowels exists, 
//vowels possibly with 'y'
boolean yRemoved = vowels.remove("y");
if(yRemoved)
    System.out.println("why was it there?!");

ArrayList cars = new ArrayList();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
String c = cars.remove(0);
System.out.println(cars);
System.out.println(c);

Depends on what was in 'vowels'

[BMW, Ford, Mazda]
Volvo

Notice, that this will automatically change the size of an aL if it contained the specified element

To remove the first element:
boolean first = aL.remove(0);

remove can return a boolean as to whether something is removed, or it can return the removed value!

  • size()

In the example above:

int n = evens.size();
System.out.println("There are " + n + " evens in the AL");

'There are 4 evens in the AL'

It's a method, not an attribute!

  • indexOf()

In the examples above:

int target = 4;
int anNdx = evens.indexOf(target);
if(anNdx >= 0)
    System.out.println(target + " is at index: " + anNdx);
else 
    System.out.println(target + " is not in the AL");

'4 is at index: 2'

ArrayLists utilize zero-based indexing

(You must provide a parameter with the correct datatype)

  • get(int ndx)
ArrayList< fibonacci = new ArrayList<String>();
int n = 6;
for(int ndx = 2; ndx <= n; ndx++){
    int f = fibonacci.get(ndx-2) + fibonacci.get(ndx-1);
    fibonacci.add(f);
}
System.out.println(fibonacci);

'[1, 1, 2, 3, 5, 8, 13]'

Send the index of the value you want to get and you'll get it

  • set(int ndx, Element)
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
...
Integer primitiveArray[] = {3, 2, 1, 0, 4, 3, 2, 7};
System.out.println(Arrays.toString(primitiveArray));

ArrayList aList = new ArrayList(Arrays.asList(primitiveArray));
System.out.println(aList);

//sort ArrayList:
Collections.sort(aList);
System.out.println(aList);

//adjust the AL:
aList.add(4, 666); //inserts a ndx=4; others move over
System.out.println(aList);

//modify the AL:
aList.set(4, 777);
System.out.println(aList);

[3, 2, 1, 0, 4, 3, 2, 7]
[0, 1, 2, 2, 3, 3, 4, 7]
[0, 1, 2, 2, 666, 3, 3, 4, 7]
[0, 1, 2, 2, 777, 3, 3, 4, 7]

Supply a 'setter' index and change the value at that location

Note in this example how we created an ArrayList from a primitive (Integer) array (see move about this in the example below

Also notice how we sorted an ArrayList using the Collections class!

  • contains(Obj)
public static boolean addElementToList(ArrayList<String> aL, 
    String elem, boolean shouldSort){
    boolean wasAdded = false;
    if(!aL.contains(elem)){
        aL.add(elem);
        wasAdded = true;
        if(shouldSort) Collections.sort(aL);
    }
    return wasAdded;
}//end addElementToList
                                            
ArrayList<String> stooges = 
    new ArrayList<String>();
stooges.add("Moe"); 
stooges.add("Larry"); 
stooges.add("Curly");
boolean added = addElementToList(stooges, "Shemp", 
    true);
if(added) 
    for(String x : stooges) 
        System.out.println(x);
                                            

Curly
Larry
Moe
Shemp

Returns true if the list contains the specified element

  • clear()
  • isEmpty()
ArrayList<Integer> evens = new ArrayList<Integer>();
evens.add(0);
evens.add(2);
evens.add(4);
evens.add(6);
evens.clear();
if(evens.isEmpty()) System.out.println("There are no more evens");
else System.out.println("There are some evens left");

'There are no more evens'

Removes all of the elements from this list. The list will be empty after this call returns.

isEmpty() returns whether or not there are any elements left in the AL.

Helpful ArrayList Manipulations:
User Method Call/Code Code/Commentary
Sort an ArrayList
//assume an ArrayList of Superheroes, heroes, exists
Collections.sort(heroes);
                                            

We just need to import the Collections library:

import java.util.Collections;

Notice that we lose the original order; in some cases you may want to make a copy before sorting!

remove all instances of an element from a list
//assume an ArrayList of letters, ltrs, exists
boolean wereRemoved = removeInstancesFromList(ltrs, "x");
if(wereRemoved) System.out.println("No more x's!");
                                            
public static boolean removeInstancesFromList(ArrayList<String> aL, String elem, boolean shouldSort){
    boolean wasRemoved = false;
    while(aL.contains(elem)){
        aL.remove(elem);
        wasRemoved = true;
        if(shouldSort) Collections.sort(aL);
    }
    return wasRemoved;
}//end removeInstancesFromList
                                            
remove last ArrayList element
//assume 'alphabet' is an aL of lc alphabetized English letters
String lastLtr = alphabet.remove(alphabet.size() - 1);
System.out.println(lastLtr);
                                                                                                                       

Because we are specifying a location in the aL, it is returning the value that was there

create an arraylist of characters from a string
String state = "mississippi";
ArrayList<Character> ltrs = toArrayListCharacters("mississippi");
System.out.println(state + " has " + ltrs.size() + " letters");
                                                                                                                                                            
public static ArrayList<Character> toArrayListCharacters(String p){
    ArrayList<Character> a = new ArrayList<Character>();
    int len = p.length();
    for(int i = 0; i < len; i++){
        char c = p.charAt(i);
        a.add(c);
    }
    return a;
}//end toArrayListCharacters
                                            
remove duplicates in an arraylist
import java.util.HashSet;
...
String state = "mississippi";
ArrayList<Character> ltrs = toArrayListCharacters("mississippi");
System.out.println(state + " has " + ltrs.size() + " letters");
ArrayList<Character> uniqueLtrs = removeDuplicates(ltrs); 
System.out.println(state + " has " + uniqueLtrs.size() + " unique letters in its name");                                                                                                                     
public ArrayList<String> removeDuplicates(){
    HashSet<String> shSet = new HashSet<String>();
    ArrayList<String> temp = new ArrayList<String>();
    for(String h: names) shSet.add(h);
    for(String x: shSet) temp.add(x);
    return temp;
}//end removeDuplicates
                                            

Note that a HashSet is a data structure that cannot have duplicates. By iterating through an AL and adding its elements to a HashSet, only unique elements will be added. Then we can iterate through the HashSet and store its elements into a temporary ArrayList. We return that and voilĂ , we have a unique set of elements from the original!

create arraylists from primitive arrays
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class ArrayArrayListDemoDriver{
    public static void main(String[] args){
        System.out.println("=== Array, ArrayList Demos ===");
        
        System.out.println("--- Integers ---");
        //dwr! to work, this must be 'Integer' not 'int'
        //int primitiveArray[] = {3, 2, 1, 0, 4, 3, 2, 7};
        Integer primitiveArray[] = {3, 2, 1, 0, 4, 3, 2, 7};
        System.out.println(Arrays.toString(primitiveArray));
        
        //technique 1
        ArrayList<Integer> aList = new ArrayList<Integer>(Arrays.asList(primitiveArray));
        System.out.println(aList);
        
        //sort primitiveArray:
        Arrays.sort(primitiveArray);
        
        //technique 2
        ArrayList<Integer> aList2 = new ArrayList<Integer>();
        Collections.addAll(aList2, primitiveArray);
        System.out.println(aList2);
        
        //adjust the AL:
        aList2.add(4, 666);
        System.out.println(aList2);
        
        System.out.println("\n--- Strings ---");
        //dwr! the 'footprint' of usage depends on data type
        String[] letters = {"a", "b", "c", "d", "e"};

        //Method 1
        List<String> letterList = Arrays.asList(letters);          
        System.out.println(letterList);
        
        //Method 1a
        ArrayList<String> letterList2 = new ArrayList<String>(Arrays.asList(letters));          
        System.out.println(letterList2);

        //Method 2
        List<String> list1 = new ArrayList<String>();
        Collections.addAll(list1, letters);
        System.out.println(list1);
        
        //Method 3
        ArrayList<String> list2 = ArrayList<String>();
        for(String text: letters) {
            list2.add(text);
        }
        System.out.println(list2);
        
        
    }//end main method
}//end ArrayArrayListDemoDriver
                                            

Note that the asList method requires Object data types to do its work!