HashSet 类的实现

package Hash;

import MyInterface.Iterator;
import MyInterface.Set;

/**
 * HashSet 类的实现
 */
public class HashSet<T> implements Set<T> {

	private static final Object PRESENT = new Object();
	private HashMap<T, Object> map;

	public HashSet() {
		map = new HashMap<T, Object>();
	}

	public boolean add(T item) {
		return map.put(item, PRESENT) == null;
	}

	public void clear() {
		map.clear();
	}

	public boolean contains(Object obj) {
		return map.containsKey(obj);
	}

	public boolean isEmpty() {
		return map.isEmpty();
	}

	public Iterator<T> iterator() {
		return map.keySet().iterator();
	}

	public boolean remove(Object item) {
		return map.remove(item) == PRESENT;
	}

	public int size() {
		return map.size();
	}

	public Object[] toArray() {
		return map.keySet().toArray();
	}

	public String toString() {
		return map.keySet().toString();
	}

}


测试类
package Hash;
import MyInterface.Iterator;
import MyInterface.Set;
public class TestHashSet {

	public static void main(String[] args) {
		HashSet<String> hs = new HashSet<String>();
		hs.add("Ad");
		hs.add("Afawed");
		hs.add("Afsd");
		hs.add("Affd");
		System.out.println(hs); // [Afsd, Ad, Affd, Afawed]
		hs.remove("Ad");
		
		Iterator<String> it = hs.iterator();
		while(it.hasNext()) 
			System.out.println(it.next());
		
		hs.clear();
		System.out.println(hs.size());
		
	}

}

你可能感兴趣的:(java hashset)