Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week111 APCS-A: Java Arrays Continued (related information in Chapter 7 of Lewis & Loftus) November 16, 2005.

Similar presentations


Presentation on theme: "Week111 APCS-A: Java Arrays Continued (related information in Chapter 7 of Lewis & Loftus) November 16, 2005."— Presentation transcript:

1 week111 APCS-A: Java Arrays Continued (related information in Chapter 7 of Lewis & Loftus) November 16, 2005

2 week112 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

3 week113 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”);

4 week114 The pets array 0 1 2 3 4 5 6 Fido Goldy pets What does pets[0].bark(); do?

5 week115 And Now… Entering Multiple Dimensions!

6 week116 2D arrays Used to represent tables of values in rows and columns 0 12 3 45678 0 1 2

7 week117 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]

8 week118 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 01 0 1 12 34 01 0 1 12 34 5

9 week119 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 rows c[0] = new int [5]; // row 0 has 5 columns c[1] = new int [3]; // row 1 has 3 columns

10 week1110 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(); }

11 week1111 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.

12 week1112 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.

13 week1113 APCS-A: Java ArrayLists and Iterators November 18, 2005

14 week1114 Checkpoint Lights Out Array Lab (Address Book) Grade Manipulator Project

15 week1115 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); }

16 week1116 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

17 week1117 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…

18 week1118 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.

19 week1119 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)

20 week1120 Some ArrayList Methods boolean add(Object o) Appends the specified element to the end of this list. addObject void clear() Removes all of the elements from this list.clear boolean contains(Object elem) Returns true if this list contains the specified element. containsObject Object get(int index) Returns the element at the specified position in this list. get int indexOf(Object elem) Searches for the first occurence of the given argument, testing for equality using the equals method. indexOfObject boolean isEmpty() Tests if this list has no elements. isEmpty int lastIndexOf(Object elem) Returns the index of the last occurrence of the specified object in this list. lastIndexOfObject Object remove(int index)remove Removes the element at the specified position in this list.

21 week1121 Array versus ArrayList ArrayArrayList BenefitObjects and primitives do not need to be cast when accessing the elements Dynamically sizeable DrawbackNot dynamically sizableMay not hold primitives and Objects usually need to be cast when accessing the element

22 week1122 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)

23 week1123 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

24 week1124 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.

25 week1125 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 }

26 week1126 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.

27 week1127 What does the API say about the Iterator methods? boolean hasNext() Returns true if the iteration has more elements. hasNext Object next() Returns the next element in the iteration. Objectnext void remove()remove Removes from the underlying collection the last element returned by the iterator

28 week1128 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!

29 week1129 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…

30 week1130 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”

31 week1131 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!

32 week1132 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 myStringList = new ArrayList ;  Now our ArrayList can hold only Objects of type String!

33 week1133 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


Download ppt "Week111 APCS-A: Java Arrays Continued (related information in Chapter 7 of Lewis & Loftus) November 16, 2005."

Similar presentations


Ads by Google