AbstractSet Class : Abstract Set « Collections « Java Tutorial






import java.io.Serializable;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

class ArraySet extends AbstractSet implements Cloneable, Serializable {
  private ArrayList list;
  public ArraySet() {
    list = new ArrayList();
  }
  public ArraySet(Collection col) {
    list = new ArrayList();
    Iterator itor = col.iterator();
    if (col instanceof Set) {
      while (itor.hasNext()) {
        list.add(itor.next());
      }
    } else {
      while (itor.hasNext()) {
        add(itor.next());
      }
    }
  }
  public Iterator iterator() {
    return list.iterator();
  }
  public int size() {
    return list.size();
  }
  public boolean add(Object element) {
    boolean modified;
    if (modified = !list.contains(element)) {
      list.add(element);
    }
    return modified;
  }
  public boolean remove(Object element) {
    return list.remove(element);
  }
  public boolean isEmpty() {
    return list.isEmpty();
  }
  public boolean contains(Object element) {
    return list.contains(element);
  }
  public void clear() {
    list.clear();
  }
  public Object clone() {
    try {
      ArraySet newSet = (ArraySet) super.clone();
      newSet.list = (ArrayList) list.clone();
      return newSet;
    } catch (CloneNotSupportedException e) {
      throw new InternalError();
    }
  }
}
public class MainClass {
  public static void main(String args[]) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new ArraySet(Arrays.asList(elements));
    Iterator iter = set.iterator();
    while (iter.hasNext()) {
      System.out.println(iter.next());
    }
  }
}
A
B
C
D
E








9.21.Abstract Set
9.21.1.Things you can do with Sets
9.21.2.AbstractSet Class
9.21.3.One Item Set