arraylist javamethods an introduction to object-oriented programming maria litvin gary litvin...
DESCRIPTION
12½ - 3 Interfaces l An interface specifies a list of one or more methods, giving only their signatures, but no code l A class implements an interface if it supplies code for all methods of that interface l If a class C implements an interface I, objects of C acquire a secondary data type, I l A class can implement several interfaces but it can extend only one classTRANSCRIPT
ArrayList
JavaJavaMethodsMethods
An Introductionto Object-Oriented Programming
Maria Litvin Gary Litvin
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
TM
Chapter 12½
12½ - 2
Objectives:
Review interfaces Learn about Comparable interface Learn about the java.util.List interface
and java.util.ArrayList class
12½ - 3
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½ - 4
Interfaces: examplepublic interface Sellable{ double getPrice (); void setPrice (double price);}
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; }}
Assumed public
implements
12½ - 5
Interfaces (cont’d) Why do we need them?
– Situation one:
public method calculateTax (Sellable obj, double rate) { return obj.getPrice() * rate; }
... GrorceryItem apple = new GroceryItem("Apple", 0.30); double tax = calculateTax(apple, 0.05); ...
More generic type of parameter more reusable code (works for any “Sellable” object)
12½ - 6
Interfaces (cont’d)
– Situation two:
private Sellable[ ] items = new Sellable[3];
items[0] = new GroceryItem(...); items[1] = new Pizza(...); items[2] = new JewelryItem(...);
Different types of objects are mixed together in the same array or list
12½ - 7
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½ - 8
Comparable (cont’d)
«interface»java.lang.Comparable
java.lang.String java.lang.Integer java.lang.Double
compareTo is based on
lexicographical order
compareTo is based on
numerical values
12½ - 9
Comparable examplepublic class UsedCar implements Sellable, Comparable{ private double myPrice;
< ... constructors and other methods... >
public int compareTo(Object other) { double diff = getPrice() - ((UsedCar) other).getPrice();
return (int)(100 * diff); // diff in cents }}
Forgetting a cast or parentheses results in a syntax error
12½ - 10
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½ - 11
List Methods (a Subset)int size();boolean isEmpty ();boolean add (Object obj);void add (int i, Object obj);Object set(int i, Object obj);Object get(int i);Object remove(int i);boolean contains(Object obj);int indexOf(Object obj);
returns true
inserts obj as the i-th value; i must be from 0 to size()
i must be from 0 to size() -1
use equals to compare objects
12½ - 12
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)
"Cat" "Hat" "Bat"
capacitysize
12½ - 13
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 wheni < 0 or i size()
12½ - 14
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½ - 15
ArrayList (cont’d) From Java API Docs:
12½ - 16
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();
ArrayList (cont’d) Example 1
Need a cast to Integer in order to call intValue
12½ - 17
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++; }
ArrayList (cont’d) Example 2
Shifts all the values after the i-th to the left and decrements the size
12½ - 18
Lab: Index Maker
One fishtwo fishRed fishBlue fish.
Black fishBlue fishOld fishNew fish.
This one hasa little star.
This one has a little car.Say! What a lotof fish there are.
A 12, 14, 15ARE 16BLACK 6BLUE 4, 7CAR 14FISH 1, 2, 3, 4, 6, 7, 8, 9, 16HAS 11, 14LITTLE 12, 14LOT 15NEW 9OF 16OLD 8ONE 1, 11, 14RED 3SAY 15STAR 12THERE 16THIS 11, 14TWO 2WHAT 15
fish.txt fishIndex.txt
12½ - 19
Index Maker (cont’d)
IndexMaker
IndexEntry
DocumentIndex
<<interface>>java.util.List
java.util.ArrayList
implementsextends
has
12½ - 20
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½ - 21
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?