Java Reference
In-Depth Information
// Make new array
String[] newItems = new String[items.length - 1];
// Add existing items except item to be removed
System.arraycopy(items, 0, newItems, 0, indexOf(item)); // First half
System.arraycopy(items, indexOf(item) + 1, newItems, indexOf(item),
items.length - indexOf(item) - 1); // Second half
// Set new array
items = newItems;
}
void showContents() {
System.out.println("Set contains " + items.length + " elements");
for (int i = 0; i < items.length; i++) {
System.out.println(" - Element " + i + ": " + items[i]);
}
}
int size() {
return items.length;
}
public static void main(String[] args) {
SetAsArray mySet = new SetAsArray();
mySet.addItem("A");
mySet.addItem("B");
mySet.addItem("C");
mySet.addItem("A");
mySet.showContents();
mySet.removeItem("B");
mySet.showContents();
mySet.addItem("D");
mySet.showContents();
}
}
As shown, the SetAsArray class provides functionality for adding, removing, and looking up
items, as well as for returning the size of the set. This example might look a bit daunting (it uses
a for loop to iterate over the array and the if construct to govern program flow, which you'll
read about in‐depth in the following chapter), but the point is that rolling data structures such as
sets by hand is frustrating, difficult, and time‐consuming. Here is the same main method, using a
HashSet :
import java.util.HashSet;
public class HashSetTester {
public static void main(String[] args) {
HashSet<String> mySet = new HashSet<String>();
mySet.add("A");
mySet.add("B");
mySet.add("C");
mySet.add("A");
Search WWH ::




Custom Search