class Set { private Comparable[] members; private int nextSlot; private static final int DEFAULT_SIZE = 10; private static final double GROWTH_FACTOR = 2.0; private static final String NL = System.getProperty ("line_separator"); public Set() { members = new Comparable[DEFAULT_SIZE]; nextSlot = 0; } public Set (int size) { members = new Comparable[size]; nextSlot = 0; } public void add (Comparable item) { if (members.length == nextSlot) grow(); int hole = nextSlot; for ( ; hole > 0; hole--) { if (members[hole-1].compareTo(item) <= 0) break; } members[hole] = item; nextSlot++; } public boolean isMember(Comparable item) { for (int index=0; index < nextSlot; index++) { if (members[index].equals(item) return true; } return false; } public Set union (Set otherSet) { Set unionSet = new Set (nextSlot + otherSet.nextSlot); int thisIndex = 0; int otherIndex = 0; while ((thisIndex < nextSlot) && (otherIndex < otherSet.nextSlot)) { // special case -- eliminate duplicate if (members[thisIndex].compareTo(otherSet.members[otherIndex] == 0) { unionSet.members[unionSet.nextSlot++] = members[thisIndex]; thisIndex++, otherIndex++; continue; } if (members[thisIndex].compareTo(otherSet.members[otherIndex] < 0) unionSet.members[unionSet.nextSlot++] = members[thisIndex++]; else unionSet.members[unionSet.nextSlot++] = otherSet.members[otherIndex++]; } while (thisIndex < nextSlot) { unionSet.members[unionSet.nextSlot++] = members[thisIndex++]; } while (otherIndex < otherSet.nextSlot) { unionSet.members[unionSet.nextSlot++] = otherSet.members[otherIndex++]; } return unionSet; } public Set intersection (Set otherSet) { Set intersectionSet = new Set (nextSlot < otherSet.nextSlot ? nextSlot : otherSet.nextSlot); int otherIndex = 0; for (int thisIndex = 0; thisIndex < nextSlot; thisIndex++) { for ( ; (otherIndex < otherSet.nextSlot) && members[thisIndex].compareTo(otherSet.members[otherIndex]) <= 0); otherIndex++) ; if (otherIndex >= otherSet.nextSlot) break; if (members[thisIndex].compareTo(otherSet.members[otherIndex]) == 0) { intersectionSet.members[insersectionSet.nextSlot++] = members[thisIndex]; otherIndex++; } } return intersectionSet; } private void grow() { Comparable[] biggerList = new Comparable[(int)(GROWTH_FACTOR *list.length)]; for (int index=0; index < nextSlot; index++) biggerList[index] = list[index]; list = biggerList; } }