



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Professor: Hanks; Class: Intro to Programming in Java; Subject: Computer Science Info Systems; University: Fort Lewis College; Term: Unknown 1989;
Typology: Study notes
1 / 5
This page cannot be seen from the preview
Don't miss anything!




Read: 4.7 (skip 4.7.2 and 4.7.3) and 4. Chapter 4 - Collections A couple of lectures ago, I said that there were two kinds of collections
private ArrayList notes; This statement declares a variable named notes that is an ArrayList. Because ArrayList is a class, we need to create an object of this type. notes = new ArrayList(); Once we have an ArrayList object, we can use its methods. Although ArrayList has many methods, we are only going to look at 3 of them: add, get, and size. add – store an object in the list size – return the number of objects in the list (kind of like the .length field of an array) get – get an object from the list (but don’t remove it) Let’s look at how an ArrayList might work. See figures 4.1 and 4.2 (page 83) Properties of ArrayLists: Variable size – an ArrayList gets bigger if necessary as we add more items It keeps track of the number of items it currently contains It maintains the order of the items. We can retrieve the items in the same order as we added them. Look back at the Notebook source – it looks pretty simple, as it contains only 1 instance variable. All the difficult work is done in the ArrayList – this is one of the great advantages of using library classes: someone else has taken the time to develop something useful, and we can use it. Abstraction again! Discuss Notebook constructor, storeNote, and numberOfNotes methods. Point out that the Notebook doesn’t keep track of the number of notes – it lets the ArrayList do that instead. Numbering with collections Did you notice anything odd or surprising when you used the showNote method? It wanted a parameter that indicated the Note number to show. What values did you have to use? What value do you have to use to display the first Note that you inserted? A value that is used to reference a particular item in a collection is called an index. In an arrayList, the value of the index ranges from 0 to size-1 – Just like the index used with array elements. Look at the showNote method – most of the code is there to make sure that you don’t try to access the ArrayList outside of its valid range.
The while statement works this way:
Lab Exercise Open the project student – it contains two classes: