Download presentation
Presentation is loading. Please wait.
1
ArrayLists Readings: 10.1 (pg. 559 – 571)
2
How would we create a list of strings?
String[] list = new String[10]? What’s wrong with this? What if we wanted our list to have more than 10 strings?
3
What’s so great about lists anyway?
Shopping list Song queue Student roster Transaction history Buddy list inbox And let’s not forget… compiler errors
4
What operations can we do with lists?
Add items Remove items Lookup items Get list size …
5
ArrayList Creating a list of strings, syntax:
ArrayList is in the java.util package. Creating a list of strings, syntax: ArrayList<String> list = new ArrayList<String>(); Creating a list of points, syntax: ArrayList<Point> list = new ArrayList<Point>();
6
Generic classes ArrayList<E> represents a family of types, which includes ArrayList<String> and ArrayList<Point> generic class: A class that takes a type parameter to indicate what kind of values will be used. Creating a list, general syntax: ArrayList<E> list = new ArrayList<E>(); ("E" is for "Element“)
7
Some ArrayList operations
Adding to a list, general syntax: list.add(object); or list.add(i, object); // add object at given index Removing from a list, general syntax: list.remove(i); // remove object at given index
8
Example Output: import java.util.*; public class ArrayListExample {
public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Alpha"); list.add("Bravo"); list.add("Charlie"); list.add("Delta"); list.add("Echo"); System.out.println(list); } Output: [Alpha, Bravo, Charlie, Delta, Echo]
9
Removing items Before: [Alpha, Bravo, Charlie, Delta, Echo]
list.remove(0); list.remove(1); After: [Bravo, Delta, Echo]??? What happened?
10
Exercise Write a static method named removeRange that takes an ArrayList and two integers (a start index and an end index) and that removes all of the elements whose index is between start, inclusive and end, exclusive.
11
Solution public static void removeRange(ArrayList list,
int start, int end) { for (int i = start; i < end; i++) { list.remove(start); } int length = end - start; for (int i = 1; i <= length; i++) {
12
How are lists implemented?
Arrays underlie ArrayLists. How do arrays accomplish that? Shifting elements, constructing new arrays Does knowing that really matter? ArrayLists implement a list abstraction.
13
What else can ArrayLists do?
14
Java API Specification
Readings: Appendix C (pg. 857 – 859)
15
Solving bigger problems
Your program needs to do X. What do you do? Two options: Write it yourself. Reuse code.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.