OOP: Collections
1
Collections in Java
• Arrays
n Has special language support
• Iterators
n Iterator (i)
• Collections (also called containers)
n Collection (i)
n Set (i),
u HashSet (c), TreeSet (c)
n List (i),
u ArrayList (c), LinkedList (c)
n Map (i),
u HashMap (c), TreeMap (c)
OOP: Collections
2
Array
• Most efficient way to hold references to objects.
• Advantages
n An array know the type it holds, i.e., compile-time type checking.
n An array know its size, i.e., ask for the length.
n An array can hold primitive types directly.
• Disadvantages
n An array can only hold one type of objects (including primitives).
n Arrays are fixed size.
2
Car
3
4
5
Car
6
7
Car
1
Car
0
index
data
OOP: Collections
3
Array, Example
• Helper class java.util.Arrays
n Search and sort: binarySearch(), sort()
n Comparison: equals()
(many overloaded)
n Instantiation: fill()
(many overloaded)
n Conversion:
asList()
class Car{};
// minimal dummy class
Car[] cars1;
// null reference
Car[] cars2 = new Car[10];
// null references
for (int i = 0; i < cars2.length; i++)
cars2[i] = new Car();
// Aggregated initialization
Car[] cars3 = {new Car(), new Car(), new Car(), new Car()};
cars1 = {new Car(), new Car(), new Car()};
OOP: Collections
4
Overview of Collection
• A collection is a group of data manipulate as a single object.
Corresponds to a bag.
• Insulate client programs from the implementation.
n array, linked list, hash table, balanced binary tree
• Like C++'s Standard Template Library (STL)
• Can grow as necessary.
• Contain only Objects (reference types).
• Heterogeneous.
• Can be made thread safe (concurrent access).
• Can be made not-modifiable.
OOP: Collections
5
Collection Interfaces
• Collections are primarily defined through a set of interfaces.
n Supported by a set of classes that implement the interfaces
• Interfaces are used of flexibility reasons
n Programs that uses an interface is not tightened to a specific
implementation of a collection.
n It is easy to change or replace the underlying collection class with
anot