import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import javax.swing.JOptionPane; /** * * @author Bill Kraynek */ public class CollectionExample { /** * @param args the command line arguments */ public static void main(String[] args) { Collection c = new MyCollection(); c.add(37); c.add(371); c.add(7); c.add(3); c.add(73); c.add(100); c.add(10); c.add(4); String out = c.contains(4) + "\n"; Iterator itr = c.iterator(); while (itr.hasNext()) { out += itr.next() + " "; itr.remove(); }// end while c.add(137); out += "\n"; for (int x : c) { out += x + " "; }// end for out += "\n" + c + "\n"; Integer[] a = {2,6,5,7,3,7}; out += contains(a,7) + "\n"; out += max(a) + "\n"; String[] b = {"2","d","abs","37"}; out += contains(b,2) + "\n"; out += max(b) + "\n"; JOptionPane.showMessageDialog(null, out); } static class MyCollection extends AbstractCollection { T[] elements; int size; public MyCollection() { elements = (T[]) new Object[5]; size = 0; } public boolean add(T x) { if (size >= elements.length) { increaseCapacity(); } elements[size++] = x; return true; } public int size() { return size; } public Iterator iterator() { return new MyIterator(); } public String toString() { trim(); return Arrays.toString(elements); } private class MyIterator implements Iterator { private int next; private boolean removeOK; public MyIterator() { next = 0; removeOK = false; } public T next() { removeOK = true; return elements[next++]; } public boolean hasNext() { return next < size; } public void remove() { if (removeOK) { for (int i = next - 1; i < size - 1; i++) { elements[i] = elements[i + 1]; }// end for size--; next--; removeOK = false; } else { throw new IllegalStateException(); } } } private void increaseCapacity() { T[] save = elements; elements = (T[]) new Object[2 * elements.length + 1]; System.arraycopy(save, 0, elements, 0, save.length); }// end increaseCapacity private void trim() { T[] save = elements; elements = (T[]) new Object[size]; System.arraycopy(save, 0, elements, 0, size); }// end trim } static boolean contains(T[] array, Object x) { return contains(array, x, 0); } static boolean contains(T[] array, Object x, int first) { if (first >= array.length) { return false; }// end if if( array[first].equals(x) ) return true; return contains(array,x,first+1); } static > T max(T[] array) { return max(array, 0); } static > T max(T[] array, int first) { if( first == array.length-1 ) return array[first]; T max = max(array,first+1); if( max.compareTo(array[first]) > 0 ) return max; return array[first]; } }