Date post: | 18-Jan-2018 |
Category: |
Documents |
Upload: | todd-clark |
View: | 220 times |
Download: | 0 times |
week11 1
APCS-A: Java
Arrays Continued(related information in Chapter 7
of Lewis & Loftus)November 16, 2005
week11 2
Checkpoint
• Project Chess project due today, please turn in
• Past homework Student/MathClass.java (practice with enums and
static Math methods)• Past lectures - what do we remember?
Arrays of primitive data types Pass by value versus pass by reference
• Past lab: Lights Out
week11 3
Creating an array of objects
Dog[] pets; //declare a Dog array variable
pets = new Dog[7]; //create the array
note, we have an array of Dog references, but no actual Dog objects! Need to make the Dog objects…
pets[0] = new Dog(“Fido”);pets[1] = new Dog(“Goldy”);
week11 4
The pets array
0 1 2 3 4 5 6
Fido Goldy
pets
What does pets[0].bark(); do?
week11 5
And Now…
Entering Multiple Dimensions!
week11 6
2D arrays
• Used to represent tables of values in rows and columns
0 1 2 3 4 5 6 7 8
0
1
2
week11 7
2d arrays in Java
• Actually are one-dimensional arrays whose elements are also one-dimensional arrays
• Usually referred to as rows by columns So the example from the last slide is a 3-by-9
array To refer to an element is: a[row][col]
week11 8
Array Initializers for 2d arrays
• int b [ ][ ] = { {1,2}, {3,4}} Grouped by rows in braces
• int b [ ] [ ] = {{ 1, 2} , { 3, 4, 5}} Creates an array with a row of two elements
and a row of three elements Row 0 is a 1-d array with two elements Row 1 is a 1-d array with three elements
0 10
11 2
3 4
0 10
11 2
3 4 5
week11 9
Array-Creation Expressions
• To create a square array:int b[ ] [ ];b = new int [3] [4];
• To create an array in which each row has a different number of columns:
int c [ ] [ ];c = new int[2][]; //create 2 rowsc[0] = new int [5]; // row 0 has 5 columnsc[1] = new int [3]; // row 1 has 3 columns
week11 10
And remember: for loops and arrays go together!
• For a 2d array, we will need nested for loops:
for(int row = 0; row < c.length; row++){for(int col = 0; col < c[row].length; col++){ System.out.print(c[row][col] + “ “);}System.out.println();
}
week11 11
Address Array: Practice with Arrays of Objects
public class AddressCard{String name;String city;int zip;public Address(String name, String city, int num){this.name = name;this.city = city;zip = num;}
} Make a simple address book. Prompt the user for the number of addresses
to put in the “book”. Use an array to store each address.. Use a loop and the Scanner class to read in each entry into the array. Have a print method to print all addresses.
week11 12
More Practice with Arrays: For later
public class Card{enum Suit {Heart, Spade, Club, Diamond}Suit mySuit;int value;public Card(Suit s, int num){
mySuit = s;value = num;
}}// Jack = 11, Queen = 12, King = 13, Ace = 1
Make a “Deck” of cards that will hold 52 cards.
week11 13
APCS-A: Java
ArrayLists and IteratorsNovember 18, 2005
week11 14
Checkpoint
• Lights Out• Array Lab (Address Book)• Grade Manipulator Project
week11 15
For each… new in Java 5
• Instead of using the regular for loop to step through each element, Java 5 gives a new kind of loop:
Dog[] myArray = new Dog[20];//pretend these have been initialized to something
for(Dog d : myArray){System.out.println(d);
}
week11 16
Intro…
• But Ms. K I don’t know how many items I am going to need to store… arrays won’t work for me!
• What should I do? I want a flexible sized collection!
And in comes…. ArrayList
week11 17
ArrayList - what’s that?
• It’s an object in the java.util package• A Class that implements a list - a flexible-
sized collection “List” is a special Java interface (we’ll talk
about interfaces later) that specifies methods and variables anything called a “List” should have
• It’s kind of like an array, but can grow and shrink And it has some limitations…
week11 18
Important Features of ArrayList
• 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 in it.
• It maintains the order of items you insert into it. You can later retrieve them in the same order.
week11 19
Some ArrayList details
• Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
• An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation (creating the space to add new elements one at a time)
week11 20
Some ArrayList Methodsboolean add(Object o)
Appends the specified element to the end of this list. void clear()
Removes all of the elements from this list.boolean contains(Object elem)
Returns true if this list contains the specified element. Object get(int index)
Returns the element at the specified position in this list. int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for equality using the equals method.
boolean isEmpty() Tests if this list has no elements.
int lastIndexOf(Object elem) Returns the index of the last occurrence of the specified object in this list.
Object remove(int index) Removes the element at the specified position in this list.
week11 21
Array versus ArrayListArray ArrayList
Benefit Objects and primitives do not need to be cast
when accessing the elements
Dynamically sizeable
Drawback Not dynamically sizable May not hold primitives and Objects usually
need to be cast when accessing the element
week11 22
Lab Assignment (For later)
• Create a Notebook object that stores notes for a user. A Note is an object that keeps track of the String data, the date
entered, and anything else you think “fits”• Internally this program will store all the notes in an
ArrayList.• It will have the following methods:
void storeNote(String note) int numberOfNotes() void showNote(int noteNumber) void removeNote(int noteNumber)
week11 23
Going through a whole collection
• Think about the Notebook problem we’ve just proposed If users can add and remove notes, the index
numbers can change, so we want a way to list all the notes with their current index numbers.
We also want a method called listAllNotes that can take into account that the list has dynamic size and can change a lot
week11 24
2 ways to go through a collection
• For an ArrayList, we could loop through similarly to what we do for an array (using the index to get each element)
• But going through all items in a collection is a common activity, so the Java API gives a way to iterate over contents of a collection.
week11 25
Iterating
• The java.util package has an Iterator object• An Iterator is an object that has methods that lets you step through
each item in a collection one at a time• This object provides two methods for iteration: hasNext and next
• Example: Using this object (assume you have an ArrayList defined called myCollection)
Iterator it = myCollection.iterator();while(it.hasNext()){
// Call it.next to get the next object //do something with that object you got
}
week11 26
Why two ways?
• For an ArrayList, either way will work and is roughly equal in terms of quality
• For other collection classes in Java, it is impossible or very inefficient to access elements by providing an index.
• The iterator solution can be used for all collections in Java, so it is an important design pattern to use.
week11 27
What does the API say about the Iterator methods?
• boolean hasNext() Returns true if the iteration has more elements.
• Object next() Returns the next element in the iteration.
• void remove() Removes from the underlying collection the last
element returned by the iterator
week11 28
Why an Iterator is even better than a for loop ….
• So let’s say that you are looping through your ArrayList of friends with a for loop and you need to delete two of them from the middle What happens? ==> your counter ends up being off because you are changing the data
structure as you go through• However, if you loop through using an Iterator -- you don’t have this
problem You can think of the iterator as an “I” beam - when you stop to remove
something, the beam stays where it is You don’t have to decrement counter in order not to miss anything
• Iterators can traverse collections more elegantly and efficiently if you are changing things as you go along!
week11 29
What is the “Object” that the next method returns?
• Object In package java.lang
• Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
• We will go into more detail soon (in December) about the Object class and why Java is set up this way…
week11 30
But I put a String in my ArrayList…
• My ArrayList has Amnesia!
• Why does the Iterator give me an Object? What can I do with that Object?
• We just learned that every class has Object as its superclass, so we need a way of saying to the Java compiler, “Hey, this thing the Iterator just got for me isn’t a plain regular Object, it is an object that I’ve put in there, and I know that it has the data type of String”
week11 31
Casting to the rescue!
• Remember casting from our int/int = double days?
• We can use casting to do this too! Tell the compiler what specific kind of object is stored
in your ArrayList
String myString = (String) it.next();
I have a String not an Object!
week11 32
But there’s more…
• We could also use the “for each” loop that I introduced at the beginning of class because it is actually just a shortcut of doing an Iterator
• The newest version of Java put in something called Generics that will fix this “amnesia” problem We won’t go into details in this class, but it’s actually really cool:
• ArrayList<String> myStringList = new ArrayList<String>; Now our ArrayList can hold only Objects of type String!
week11 33
Lab time
• We will practice ArrayLists later - but keep the ideas fresh in your memories!
• Today: Finish the Address book array lab Work on Array Project (Grade Manipulator) Remember: Quiz on Tuesday - focusing on
Arrays