Docsity

Array Lists - Lecture Slides | Computer Science II | CS 112, Study notes of Computer Science

Partial preview of the text

Download Array Lists - Lecture Slides | Computer Science II | CS 112 and more Study notes Computer Science in PDF only on Docsity!

Intro to Programming II

ArrayLists

Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science โ€” University of San Francisco โ€“ p.1/

The ArrayList class

Last time, we learned about how to use arrays in Java. Java also provides an ArrayList class that can helpmanage arrays. ArrayList is a generic container. That means that we can use the same container tostore different kinds of elements. Department of Computer Science โ€” University of San Francisco โ€“ p.2/

The ArrayList class

Notice that we declared an initial array size. The array is then able to grow dynamically beyond that. Itโ€™s better to allocate in advance if we can. We can also remove elements, and access them. We can also add in the middle of a list: band.add(1, โ€˜โ€˜ringoโ€™โ€™); Department of Computer Science โ€” University of San Francisco โ€“ p.4/

Accessing elements

get(index) lets us access the element at a particular index. Elements in an ArrayList are stored as Objects

This means that we need to cast them back to Strings. Canโ€™t store primitives. String name = (String)band.get(2); Department of Computer Science โ€” University of San Francisco โ€“ p.5/

Other methods

also: size() - tells us how many elements are in the array. isEmpty() - tells us whether thereโ€™s anything in the list. contains(Object o) - tells us whether an object is in thelist. clear() - removes everything. Department of Computer Science โ€” University of San Francisco โ€“ p.7/

Specifying element types

If we want to avoid casting elements, we can also definethe ArrayList to accept particular sorts of objects: Java 1.5 only ... ArrayList al = new ArrayList(3); al.add("john");al.add("paul");al.add("george");al.add("ringo");String name = al.get(2); System.out.println(name); Department of Computer Science โ€” University of San Francisco โ€“ p.8/