Docsity

Arrays and ArrayLists in Java: Understanding Object References and Iterators - Prof. Orlen, Lab Reports of Computer Science

Partial preview of the text

Download Arrays and ArrayLists in Java: Understanding Object References and Iterators - Prof. Orlen and more Lab Reports Computer Science in PDF only on Docsity!

CS121/IS

Collections … Revisited Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors

REMINDER

  • There is no class meeting on Thursday April 16 – Please work on the labs!
  • You should aim to get lab 1 and the go shopping question in lab 2 finished this week.
  • Read the project description. If you are going to be working in a pair you have to tell me your pairs on Tuesday 21 April…

A Recap on Arrays

  • Arrays are objects
  • When an array is passed as a parameter to a method,

we use an alias of the original (ORV) – you will learn

all about ORVs next week…

  • Arrays can hold primitive types or variables that reference objects (i.e. class types)
  • All elements stored in an array have the same type
  • When we use the new operator to create an array, we give it a type & a size – this is fixed int[] grades = new int[8];

Array of Cars for the Car Race?

Car[] cars = new Car[size];

  • cars is the variable for accessing the collection of cars
  • Car[] is the type of the cars variable – an array holding Car objects
  • new Car[size] makes an array object that can hold as many Car objects as you state the size to be (it actually holds references to the Car objects)
  • = well, that makes sure that the cars variable is assigned to this array object we just made

Important!

• The array declaration DOES NOT

create the array objects … you

have to create them separately

Arrays of Objects (ii)

classDogs[0] = new Dog(); classDogs[1] = new Dog(); Actually an array of references to objects Dog[] type classDogs Dog array object (Dog[]) Heap 0 1 2 3 4 5 Dog object Dog object

Reminder!!!

  • ALL the code in the text book is available for you to download and experiment with. DO NOT FORGET THIS… it is useful to do this and to play around with this code!
  • http://duke.csc.villanova.edu/jss1/examples.html
  • Please look at the code in Chapter 7 on this site - download CD.java, CDCollection.java and Tunes.java - run them, try changing them, try adding a method to delete a CD from the collection and to find a CD in the collection based on a title string (Hint - you do this in the CDCollection class). Could you write a program to define students, a collection of students, and a driver class to add new students to a collection, change their grades, check who has the highest grade, etc.? It is the same basic structure and principle as the CD program!

The ArrayList Class

  • Similar to arrays, but:
    • Not fixed in size – they grow & shrink with the contents (indices adapt)
    • Only stores references to objects (not primitives)
    • Can store references to multiple types of object
    • Can store references to primitives if they are appropriately wrapped (remember Integer?)
    • Can be less efficient than plain old arrays
    • Objects forget their type … you have to find this out when they come out … use obj.getClass() Must import java.util.ArrayList

Actually implemented using arrays

Creating & Using an ArrayList

  • Create an ArrayList object: ArrayList dogs = new ArrayList(); //empty
  • Create objects to put into the ArrayList: Dog myDog = new Dog();
  • Call its methods: dogs.add(myDog); //grows a slot to hold a dog object reference variable int size = dogs.size(); //returns 1 Dog d = (Dog)dogs.get(0); //remember to cast - I can do this because I know I am only dealing with dogs! dogs.remove(myDog); //shrinks

Examples

  • Using an array of objects to do some shopping
  • Using an ArrayList to do some shopping: try the shopping again question in lab ArrayList is one of many

collections classes in Java (see also

Vector, LinkedList, HashSet & others) – a collection is actually an object that represents a group of objects – find out about the Java Collections Framework -Note I am happy you ignoring ArrayList for now if it is too much as arrays are fine for your project! Hooks to CS

Iterating Over a Collection

  • Common to want to examine every item in a collection public void getDogs(){ int index = 0; while(index<dogs.size()){ System.out.println(dogs.get(index)); index++; } }

Iterators

  • An iterator is an object designed to provide functionality to iterate over a collection – luckily it is built-in, just: import java.util.Iterator;
  • ArrayList has a method to give you an Iterator object:

Iterator it = yourCollectionName.iterator()

  • The Iterator class has 3 methods:
    • hasNext() – are there objects left in collection? Returns boolean
    • next() - returns reference to the next object
    • remove() – removes last object returned by next()
  • Call these methods on the it object (i.e. it.next()) Another nifty thing like your Scanner!

What is Iterator?

  • Iterator is actually an interface that Java Collections classes implement
  • This means that, so long as you provide concrete implementations for the hasNext(), next() & remov e() methods, you can make any class you write implement this interface
  • It is up to you to decide what order objects would be returned by next()
  • ArrayList does this all for you…and is ready to go! That makes it nice

Interfaces

  • An interface lists the public methods available for interacting with an object by declaring abstract methods
  • A class implements an interface if it provides an implementation for each of the abstract methods
  • A class can implement many interfaces
  • We will look in detail at interfaces later in CS606 – they are CRITICAL for good maintainable design Examine the code in listings 5.9 - 5.11 ( rd ed.) or 6.8-6.10 ( th
  • ed.)