Professional Documents
Culture Documents
Collections API
Collections API
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Copyright © 1998 Purple Technology,
Inc. 6-9
Overview: Core Interfaces
• Collection
• Set
• List
• Map
• SortedSet
• SortedMap
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Copyright © 1998 Purple Technology,
Inc. 6-10
Overview: Utilities
• Utility Interfaces
– Comparator
– Iterator
• Utility Classes
– Collections
– Arrays
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Copyright © 1998 Purple Technology,
Inc. 6-11
Collections and Interfaces
• Advantages
– An array knows the type it holds, i.e., compile-time
type checking.
– An array knows its size, i.e., ask for the length.
– An array can hold primitive types directly.
• Disadvantages
– An array can only hold one type of objects (including
primitives).
– Arrays are fixed size.
Iterator it = cars.iterator();
while (it.hasNext())
System.out.println ((Car)it.next());
package weiss.ds;
public class MyContainer {
Object [] items:
int size;
public MyContainerIterator iterator ( ) {
return new MyContainerlterator( this );
}
// Other methods
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-44
Class Object java.lang.Object
package weiss.ds;
public class MyContainer {
Object[] items;
int size;
public Iterator iterator () {
return new MyContainerIterator (this);
}
// Other methods
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-50
Interface Iterator
package weiss.ds;
public interface Iterator {
boolean hasNext();
Object next();
}
MyContainerIterator
private MyContainer container;
MyContainerIterator (MyContainer c) {
container = c;
}
public boolean hasNext() {
return current < container.size;
}
public Object next() {
return container.items [current++];
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-52
Main Method
public static void main (String [] args) {
MyContainer v=new MyContainer();
v.add( “3”);
v.add (“2”);
System.out.println ("Container contents: ");
Iterator itr = v.iterator ();
while (itr.hasNext ())
System.out.println (itr.next());
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-53
The List Interface
public interface List extends Collection {
Object get (int index);
Object set (int index, Object element); // Optional
void add (int index, Object element); // Optional
Object remove (int index); // Optional
abstract boolean addAll (int index, Collection c);
• Implemented by:
– ArrayList, LinkedList, Vector