001: /*
002: * Copyright 2007 Google Inc.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005: * use this file except in compliance with the License. You may obtain a copy of
006: * the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013: * License for the specific language governing permissions and limitations under
014: * the License.
015: */
016: package java.util;
017:
018: import java.io.Serializable;
019:
020: /**
021: * Implements a set in terms of a hash table. <a
022: * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html">[Sun
023: * docs]</a>
024: *
025: * @param <E> element type.
026: */
027: public class HashSet<E> extends AbstractSet<E> implements Set<E>,
028: Cloneable, Serializable {
029:
030: private transient HashMap<E, Object> map;
031:
032: public HashSet() {
033: map = new HashMap<E, Object>();
034: }
035:
036: public HashSet(Collection<? extends E> c) {
037: map = new HashMap<E, Object>(c.size());
038: addAll(c);
039: }
040:
041: public HashSet(int initialCapacity) {
042: map = new HashMap<E, Object>(initialCapacity);
043: }
044:
045: public HashSet(int initialCapacity, float loadFactor) {
046: map = new HashMap<E, Object>(initialCapacity, loadFactor);
047: }
048:
049: /**
050: * Protected constructor to specify the underlying map. This is used by
051: * LinkedHashSet.
052: *
053: * @param map underlying map to use.
054: */
055: protected HashSet(HashMap<E, Object> map) {
056: this .map = map;
057: }
058:
059: @Override
060: public boolean add(E o) {
061: Object old = map.put(o, this );
062: return (old == null);
063: }
064:
065: @Override
066: public void clear() {
067: map.clear();
068: }
069:
070: public Object clone() {
071: return new HashSet<E>(this );
072: }
073:
074: @Override
075: public boolean contains(Object o) {
076: return map.containsKey(o);
077: }
078:
079: @Override
080: public boolean isEmpty() {
081: return map.isEmpty();
082: }
083:
084: @Override
085: public Iterator<E> iterator() {
086: return map.keySet().iterator();
087: }
088:
089: @Override
090: public boolean remove(Object o) {
091: return (map.remove(o) != null);
092: }
093:
094: @Override
095: public int size() {
096: return map.size();
097: }
098:
099: @Override
100: public String toString() {
101: return map.keySet().toString();
102: }
103:
104: }
|