Download presentation
Presentation is loading. Please wait.
Published byBernice McKinney Modified over 9 years ago
1
Chapter 4 Grouping Objects
2
Flexible Sized Collections When writing a program, we often need to be able to group objects into collections It is typical that the number of items to be stored will vary over time We could create a class with a lot of fixed fields, but in general this will not work
3
Personal Notebook Example We will model a personal notebook Allow notes to be stored No limit to the number of notes stored Show individual notes Tells how many notes are stored
4
Library Classes One feature of OO languages, is the accompanying class libraries Library typically contain hundreds or thousands of different classes Java calls these libraries packages We use library classes exactly the same way we would our own classes Instances are constructed using new, and the classes have fields, constructors and methods
5
Actual Code Let’s look at the Notebook class code. Notebook Project Notebook Project Notebook Project The very first line shows how we access the package, using an import statement import java.util.ArrayList; Import statements must always be placed before class definitions in a file. Once a class name has been imported, we can use that class as if it were our own.
6
Object Structures with Collections There are at least three important features It is able to increase its internal capacity as required: as more items are added, it simply makes enough room for them. It keeps its own private count of how many items it is currently storing. Its size method returns the number of objects currently stored It maintains the order of items you insert into it. You can later retrieve them in the same order.
7
Numbering within Collections It is necessary to use values starting at zero. Items are stored in the ArrayList starting a number position zero The position is known as the index First is given index 0, the next is index 1, … It is a common mistake to try to access a collection outside the valid indices.
8
Removing Elements When a user wants to remove an note, we can invoke the remove method of the notebook object One complication of the removal process is that it can change the index values at which notes are stored If a note with a low index value is removed, then the collection moves all notes forward to fill the hole. Furthermore, it is possible to insert into other than at the end.
9
Processing a whole collection It would be useful to list all the notes in the notebook it find where all of them are We have the need to do something several times, but the number of times depends upon circumstances that vary. The solution is the while loop; one of Java’s loop statements
10
The while loop A while loop is one way to perform a set of actions repeatedly, without having to write those actions more than once. Here is a general format while ( loop condition ) { loop body //statements you want to //repeat}
11
Example /* *List all notes in the notebook *List all notes in the notebook */ */ public void listNotes() { int index = 0; while ( index < notes.size() ) {System.out.println(notes.get(index));index++;}}
12
While vs. If Do not confuse a while loop with an if. Although they look similar, they operate in very different ways The biggest difference is that once the body of the loop has been executed for the first time, we go back to the test again to see if the body should be executed.
13
Iterators Examining every item in a collection is a very common activity. The ArrayList class supplies an iterator method that supplies an Iterator object that allows us to iterate over the collection We must add another import statement to use the iterator object import java.util.Iterator;
14
Iterators An Iterator supplies two methods to iterate over a collection: hasNext and next Iterator it = myCollection.iterator(); while ( it.hasNext() ) { //call it.next() to get the //next object and do something //with that object }
15
Indices vs. Iterators We have seen approaches to accessing elements in an ArrayList In this example, both seem equally adequate Java supplies many other collections that are not as straight foreword It may also be inefficient or impossible to access elements through indices. All Java collections have iterators
16
The Auction System Example The Auction System Example The Auction System Example The Auction System Example highestBid == null null is a Java key word and means ‘no object’ When a field is an object type and it is not explicity initialized in a constructor, that field will contain the value null
17
Casting Casting is an important feature of Java Lot lot = (Lot) it.next(); A cast consists of the name of a type written alone between a pair of parentheses Casting is commonly seen when retrieving objects from a collection This is required because collections can store any type of object Casting makes it clear what type of object it is
18
Who? Anonymous Object When you need to create an object to add to a collection You can create an anonymous object to take care of this Lot furtherLot = new Lot( nextLotNumber, description); lots.add(furtherLot); or lots.add(new Lot( nextLotNumber, description));
19
Fixed-size Collections When you do know the number of items to store at the time you write the program. You can used a fixed-sized collection In Java the fixed-sized collection is called an Array
20
Arrays Arrays are one of the oldest ways to store data They come with some special syntax to access elements in the array Another type of loop is often used to process elements in an array. Log Analyzer Project Log Analyzer Project Log Analyzer Project
21
Declaring Array Variables To declare a variable of an array type private int[ ] hourCounts; Notice the brackets [ ] Then to create the array object, you use new just like all other object creations hourCount = new int[24]; Notice the number between the brackets
22
Using Array Objects You access individual array elements by indexing into the array An index is a number between 0 and one less then the number used to create the array labels[6] machines[0] people[x+10-y]
23
Indices You can use an array access anywhere you can use a variable of the same type labels[5] = “Quit”; double half = readings[0] / 2; System.out.println(people[3].getName()); machines[0] = new TicketMachine(500);
24
The for Loop The for loop is an alternative choice to the while loop It is particularly appropriate when We wish to execute a set of commands a fixed number of times We need a variable inside the loop whose value changes by a fixed amount
25
The for Loop: An example for( int hour=0; hour<hourCounts.length; hour++) { System.out.println(hour + “: ” + hourCounts[hour]); }
26
Quiz Write a class for a Person that will store a first name and a last name. You do not need to write any methods, just the private fields and the class wrapper.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.