ArrayList class
An ArrayList can be visualized as a linear list of objects at index
positions
• for example 0, 1, 2, 3
[Joe, Jasper, Dick, Abigail]
ArrayList is a data structure that grows and shrinks gracefully
• you can add/remove objects as necessary
ArrayList is a collection of objects
• we will focus on objects of type String
• to hold data of a primitive data type (e.g. int) you need to use a
wrapper class (e.g. Integer, Double, Boolean, Character) where
wrapper objects contain data of a primitive data type
R McFadyen ACS-1903 1
ArrayList class
ArrayList methods
[Link](“Jaime”);
R McFadyen ACS-1903 2
ArrayList class
ArrayList methods
Focus on: add, contains, get, indexOf, set, size
R McFadyen ACS-1903 3
ArrayList class
Displaying a list
ArrayList < String > people =new ArrayList () ;
// add some names
people . add ("Joe") ;
people . add ("Jasper") ;
people . add ("Dick") ;
people . add ("Abigail") ; whole list is displayed
[Link](people);
[Joe, Jasper, Dick, Abigail ]
R McFadyen ACS-1903 4
ArrayList class
The enhanced for
a variation on the for
used to iterate through all elements
cannot change anything
Example: iterate through an ArrayList
people =new ArrayList () ; simpler syntax
than for
// add some names
people . add ("Joe") ;
people . add ("Jasper") ;
people . add ("Dick") ;
people . add ("Abigail") ;
for(String s : people) [Link](s+ " ");
R McFadyen ACS-1903 5
ArrayList class
Example
Consider the program [Link] from previous chapter
Let’s modify it
…………………… replace [Link] with a Shakespeare work
google it … shakespeare mit
…………………… to put the tokens into a list
…………………… to put each token into list only once (list is now a vocabulary)
…………………… add another list to keep track of frequencies for each word
Which word appears most often… highest frequency
R McFadyen ACS-1903 6