Java Reference
In-Depth Information
Collections
A large part of the classes contained in the java.util package belong to the Java's collections
framework (the JCF). The Collections API provides a number of general‐purpose data structures,
which generally can be described as “better alternatives for arrays.” One of these, the HashSet , you
briefly encountered in the last Try It Out, as a simple way to keep a set of objects.
To illustrate why Java's Collections API is so useful, consider this example of how to implement a set
of Strings , using only arrays:
class SetAsArray {
String[] items;
SetAsArray() {
items = new String[] {};
}
int indexOf(String item) {
// Check if item is already present
for (int i = 0; i < items.length; i++) {
if (items[i].equals(item)) {
return i;
}
}
return -1;
}
boolean hasItem(String item) {
return indexOf(item) > -1;
}
void addItem(String item) {
if (hasItem(item)) {
// Item already present
return;
}
// Make new array
String[] newItems = new String[items.length + 1];
// Add existing items
System.arraycopy(items, 0, newItems, 0, items.length);
// Add item to new array
newItems[newItems.length - 1] = item;
// Set new array
items = newItems;
}
void removeItem(String item) {
if (!hasItem(item)) {
// Item not present
return;
}
 
Search WWH ::




Custom Search