

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 / 3
This page cannot be seen from the preview
Don't miss anything!


Lab Comments Discuss isEmpty() method: most people had something like: if ( notes.size() == 0 ) // or ( numberOfNotes() == 0 ) { return true; } else { return false; } Discuss simplifying this. ArrayList Last time we looked at the ArrayList class, which is provided by the Java library. It is a type of Collection, which means that it can be used to store objects of some other type. What are some of the methods provided by the ArrayList? add – store an object at the end of the list size – return the number of objects in the list get – get an object from the list (but don’t remove it) 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. The ArrayList is an example of a generic or parameterized class. This means that when we create an ArrayList object, we have to specify the type of objects that will be stored in the ArrayList. Let's look at some other declarations: private ArrayList
When we call the add method, what do we need to pass to it? When we call the get method, what is the type of object that will be returned? Accessing all of the elements in an ArrayList – The 'foreach' statement Let's go back to the Notebook example. We can create a Notebook, add Notes to it, and display the individual Notes. What would I need to do to write a method that prints all of the Notes in the Notebook? We could just call showNote(0), showNote(1), showNote(2), … What’s wrong with this approach? The Java language includes several ways to iterate through a collection of items. These allow us to repeat a set of statements for each item in a collection. The first of these is the foreach loop. for ( ElementType elementName : collection ) { loop body use elementName in here } Basically, this says something like: For each element in the collection, execute the statements in the loop body. Question: how many times are the statements in the loop body executed? elementName is a LV – scope is the foreach loop. Examples: