16
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 10 - 1 Chapter 10 Using arrays to create collections ArrayList class

Chapter 10

Embed Size (px)

DESCRIPTION

Using arrays to create collections ArrayList class. Chapter 10. Collections. There are many examples of programs that need many objects of a particular type A class roster needs many Student objects A CD object needs many songs A photo album needs many photos We can use arrays for this - PowerPoint PPT Presentation

Citation preview

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 1

Chapter 10

Using arrays to create collections

ArrayList class

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 2

Collections

• There are many examples of programs that need many objects of a particular type– A class roster needs many Student objects

– A CD object needs many songs

– A photo album needs many photos

• We can use arrays for this– How do we deal with the fact that we don't know ahead of

time how many objects there will be?

– Some kinds of collections change size frequently

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 3

What does a Collection class look like?

public class ItemCollection {

private Item [] collection;

private int size, capacity;

public ItemCollection() {…}

public void add( Item item) {…}

public Item get( int index) {…} …}

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 4

Dynamic Arrays

• Create the array with some standard sizeItem [] collection = new Item[capacity];

• Use a counter variable to keep track of the number of elements which are not null;

• Each time you add an item, put it in the next available element and increment the counter.collection[size] = newItem;

size++;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 5

Dynamic Arrays

• Before adding a new item, check to see if there is room• If the array is full, make a bigger array and copy the

elements from the originalif (size == capacity)

Item [] newArray = new Item[2*capacity];

for (int i=0; i< size; i++)

newArray[i] = collection[i];

collection = newArray;

capacity *= 2; }

// add element as above

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 6

JCF Lists

• JCF includes two classes that support methods to maintain a collection of objects as a linear list

L = (l0, l1, l2, . . . , lN)

• We can add to, remove from, and retrieve objects in a given list.

• A list does not have a set limit to the number of objects we can add to it.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 7

List Methods

• Here are five of the 25 list methods:

Returns the number of elements in the list

int size ( )

Removes the element at position idx

boolean remove ( int idx )

Returns the element at position idx

Object get ( int idx )

Clears this list, i.e., make the list empty

void clear ( )

Adds an object o to the list

boolean add ( Object o )

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 8

Using Lists

• To use a list in a program, we must create an instance of one of the List classes.– ArrayList

– LinkedList

• The ArrayList class uses an array to manage data.• The LinkedList class uses a technique called

linked-node representation.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 9

Sample List Usage

• Here's an example of manipulating a list:import java.util.*;

ArrayList<Person> friends;

Person person;

friends = new ArrayList<Person>( );

person = new Person("jane", 10, 'F');

friends.add( person );

person = new Person("jack", 6, 'M');

friends.add( person );

Person p = friends.get( 1 );

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 10

How to process the elements of a list?

• Use a for loop

for (int i=0; i<list.size(); i++)

process( list.get(i));

• Use for in

for (BaseType element : list)

process( element);

• Use an iterator

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 11

Using an Iterator

• The iterator method of ArrayList returns an object you can use to loop through all the elements of the listIterator<Person> iter = friends.iterator();

while (iter.hasNext())

System.out.println( iter.next());

• The next() method returns each element in turnPerson p = iter.next();

• Use hasNext() to determine when all the elements of the list have been processed

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 12

Interfaces

• Sometimes we have a number of classes that should

have a common set of methods.

• All lists should have methods like add, get, size, …

• Interfaces provide a way to specify a set of methods

that a group of classes should have in common.• A Java interface defines only behavior

– It includes headers for public methods (no method bodies)

– It does not include any data members except public constants

– No instances of a Java interface can be created

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 13

Interfaces in Java

• The Java libraries include many interfaces

• There is a List interface that includes all the methods needed by

lists

• Both ArrayList and LinkedList implement List

– They have the same methods

List<Person> list;

list = new ArrayList<Person>;

list = new LinkedList<Person>;

– The code works independent of which way you instantiated list

– This is an example of polymorphism

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 14

Java Interfaces

• Template for an interfacepublic interface <interfaceName> {

public <returnType> <methodName>(

<paramList>);

public final <constType> constName

= <constValue>;

}

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 15

Using an interface

• Use the implements keyword header of a class that needs to

have all the methods of the interface

• Implement (provide code for) each method in the interfacepublic class <implementingClassName>

implements <interfaceName> {

public <returnType> <methodName>(

<paramList>){

// code for method

}

// add any other methods and data that is

// appropriate for the class

}

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 10 - 16

Using an interface type

• You can use an interface type as the type for a reference (object) variable<interfaceName> <identifier>;

• You have to instantiate the object using a class that implements the interface<identifier>

= new <implementingClassName>();

• Now you can only call the methods that appear in the interface.