1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| public class ArraySet<T> implements Iterable<T>{ private T[] items; private int size;
public Iterator<T> iterator(){ return new ArraySetIterator(); } private class ArraySetIterator implements Iterator<T>{ private int index; public ArraySetIterator(){ index = 0; }
public boolean hasNext(){ return index < size; }
public T next(){ T returnItem = items[index]; index++; return returnItem; }
}
public ArraySet(){ items = (T[]) new Object[100]; size = 0; }
public boolean contains(T x){ for(int i = 0;i<size;i++){ if(x.equals(items[i])){ return true; } } return false; }
public void add(T x){ if(x == null){ throw new IllegalArgumentException("cannot add null yo the set"); } if(contains(x)){ return; } items[size] = x; size++; }
public int size(){ return size; } @Override public String toString(){ String returnString = "{"; for(T item: this){ returnString += item.toString(); returnString += ", "; return returnString; } returnString += items[size-1]; returnString += "}"; return returnString; }
@Override public boolean equals(Object other){ if(other == this){ return true; } if(other == null){ return false; }
if(other.getClass() != this.getClass()){ return false; } ArraySet<T> o = (ArraySet<T>) other; if(o.size() == this.size()){ return false; } for(T item: this){ if(!o.contains(item)){ return false; } } return true; }
public static void main(String[] args) { ArraySet<Integer> a = new ArraySet<Integer>(); a.add(5); a.add(10); a.add(15);
Iterator<Integer> iterator = a.iterator(); while(iterator.hasNext()){ int i = iterator.next(); System.out.println(i); }
for(int i : a){ System.out.println(i); } } }
|