Chapter 6: ArrayLists
Presentation slides for
Java Software Solutions
for AP* Computer Science A
2nd Edition
by John Lewis, William Loftus, and Cara Cocking
Java Software Solutions is published by Addison-Wesley
Presentation slides are copyright 2006 by John Lewis, William Loftus, and Cara Cocking. All rights reserved.
Instructors using the textbook may use and modify these slides for pedagogical purposes.
*AP is a registered trademark of The College Entrance Examination Board which was not involved in the production of, and does not endorse, this product.
The ArrayList Class
2
Specifying an ArrayList Element Type
Example // Declare and Instantiate
ArrayList<Integer> list = new ArrayList<Integer>( );
ArrayList<String> aList = new ArrayList<String>( );
//Declare and initial capacity
ArrayList<String> a = new ArrayList<String>(25);
** default initial capacity of 10
3
Wrapper Class
ArrayList<Integer> a = new ArrayList<Integer>();
int[] someints = { 5, 2, 5, 7, 5, 8, 5, 2 };
Primitive data type | Wrapper Class |
int | Integer |
double | Double |
boolean | Boolean |
Auto-Boxing and Unboxing
intValue( ) doubleValue( )
* Convert Integer to int
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
ArrayList Efficiency
6
Common Methods
ArrayList<E> instance methods
size( ) void clear()
E get( int index ) vs. E set( int index, E x )
boolean add( E x ) vs. void add( int index, E x )
Common Methods
E remove( int index )
For Each
for ( String name : names )" expression is read as "for each String name in names".
//Error Message
ConcurrentModificationException
"Don't change the size of this ArrayList while I'm iterating my way along it!"
//Solution
use a regular for loop
List<E> Interface
See Interface
Practice
Ex. 115 - slide 12 ArrayList