Download Ch12.5 - ComSciGate

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java
Methods
TM
Maria Litvin
Gary Litvin
An Introduction
to Object-Oriented Programming
Chapter 12½
ArrayList
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
Objectives:

Review interfaces

Learn about Comparable interface

Learn about the java.util.List interface
and java.util.ArrayList class
12½ - 2
Interfaces

An interface specifies a list of one or more methods,
giving only their signatures, but no code

A class implements an interface if it supplies code for
all methods of that interface

If a class C implements an interface I, objects of C
acquire a secondary data type, I

A class can implement several interfaces but it can
extend only one class
12½ - 3
Interfaces: example
Assumed
public
public interface Sellable
{
double getPrice ();
void setPrice (double price);
}
implements
public class GroceryItem implements Sellable
{
private double myPrice;
< ... constructors and other methods not shown >
public double getPrice () { return myPrice; }
public void setPrice (double price) { myPrice = price; }
}
12½ - 4
Interfaces (cont’d)

Why do we need them?
– Situation one:
More generic type
of parameter 
more reusable code
(works for any
“Sellable” object)
public method calculateTax (Sellable obj, double rate)
{
return obj.getPrice() * rate;
}
...
GrorceryItem apple = new GroceryItem("Apple", 0.30);
double tax = calculateTax(apple, 0.05);
...
12½ - 5
Interfaces (cont’d)
– Situation two:
Different types of
objects are mixed
together in the
same array or list
private Sellable[ ] items = new Sellable[3];
items[0] = new GroceryItem(...);
items[1] = new Pizza(...);
items[2] = new JewelryItem(...);
12½ - 6
Comparable Interface
public interface Comparable
{
/**
* Returns a positive integer if this is
* "greater than" other, a negative integer if
* this is "less than" other, and 0 if this is
* "equal" to other
*/
int compareTo(Object other);
}
Kind of like
this “minus” other
12½ - 7
Comparable (cont’d)
«interface»
java.lang.Comparable
java.lang.String
compareTo is
based on
lexicographical
order
java.lang.Integer
java.lang.Double
compareTo is
based on
numerical values
12½ - 8
Comparable example
public class UsedCar
implements Sellable, Comparable
{
private double myPrice;
< ... constructors and other methods... >
public int compareTo(Object other)
{
double diff = getPrice() ((UsedCar) other).getPrice();
Forgetting a
cast or
parentheses
results in a
syntax error
return (int)(100 * diff); // diff in cents
}
}
12½ - 9
java.util.List Interface

The List library interface describes a list of objects in
abstract terms

In a list, objects are arranged in sequence
obj0, obj1, ..., objn-1

In Java, a list holds references to objects

A list can contain duplicate objects (both
obj1.equals(obj2) and obj1 == obj2)
12½ - 10
List Methods (a Subset)
int size();
boolean isEmpty ();
boolean add (Object obj);
returns true
void add (int i, Object obj);
inserts obj as the
i-th value; i must
be from 0 to size()
Object set(int i, Object obj);
Object get(int i);
Object remove(int i);
boolean contains(Object obj);
int indexOf(Object obj);
i must be from 0 to
size() -1
use equals to
compare objects
12½ - 11
java.util.ArrayList

Implements List using an array

Keeps track of the list capacity (the length of the
allocated array) and list size (the number of
elements currently in the list)
capacity
size
"Cat" "Hat" "Bat"
12½ - 12
ArrayList (cont’d)

Automatically increases (doubles) the capacity when
the list runs out of space; allocates a bigger array and
copies all the values into it

get(i) and set(i, obj) are efficient because an array
provides random access to its elements

Throws IndexOutOfBoundsException when
i < 0 or i  size()
12½ - 13
ArrayList (cont’d)

ArrayList holds objects (of any type)

If you need to put ints or doubles into a list, use a
standard Java array or convert them into Integer or
Double objects

You have to remember what types of objects your put
into the list and may need to cast a retrieved object
back into its type
12½ - 14
ArrayList (cont’d)

From Java API Docs:
12½ - 15
ArrayList (cont’d)

Example 1
ArrayList list = new ArrayList ();
list.add (new Integer(1));
list.add (new Integer(2));
list.add (new Integer(3));
int sum = 0;
for (int i = 0; i < list.size(); i++)
sum += ((Integer) list.get(i)) . intValue();
Need a cast to Integer
in order to call intValue
12½ - 16
ArrayList (cont’d)

Example 2
ArrayList words = new ArrayList (4);
words.add ("One");
words.add ("Fish");
words.add ("Two");
words.add ("Fish");
int i = 0;
while (i < words.size() )
{
if ( ”Fish".equals (words.get(i)) )
words.remove(i);
else
i++;
}
Shifts all the values
after the i-th to the left
and decrements the
size
12½ - 17
Lab: Index Maker
fish.txt
One fish
two fish
Red fish
Blue fish.
Black fish
Blue fish
Old fish
New fish.
This one has
a little star.
This one has a little car.
Say! What a lot
of fish there are.
fishIndex.txt
A 12, 14, 15
ARE 16
BLACK 6
BLUE 4, 7
CAR 14
FISH 1, 2, 3, 4, 6, 7, 8, 9, 16
HAS 11, 14
LITTLE 12, 14
LOT 15
NEW 9
OF 16
OLD 8
ONE 1, 11, 14
RED 3
SAY 15
STAR 12
THERE 16
THIS 11, 14
TWO 2
WHAT 15
12½ - 18
Index Maker (cont’d)
<<interface>>
java.util.List
IndexMaker
extends
DocumentIndex
implements
java.util.ArrayList
has
IndexEntry
12½ - 19
Review:





How is an interface different from a class?
Can a class implement several interfaces?
Can an interface have more than one method?
If C is a class, when is the following statement
valid?
Comparable x = new C();
What are the methods of Comparable?
12½ - 20
Review (cont’d):




Name the List methods that can add a value to
the list.
Name the List methods that can tell you whether
a given value is in the list.
In an ArrayList, should the indices be less than
the size or less than the capacity?
What happens when the size of a List equals the
capacity and you try to add a value?
12½ - 21