public class HashTableSet {
	
	private static final double MAX_ALPHA = 0.75;
	
	private Object T[];
	private int nElements;
	/**
	 * @param size
	 */
	public HashTableSet(int size) {
		
		T = new Object[size];
		
	}
	protected int h(Object x, int i) {
		return (x.hashCode() + i) % T.length;
	}
	
	public void insert(Object x) {
		
		if ((nElements + 1) > MAX_ALPHA * T.length)
			grow();
		
		int i = 0, j = h(x,i);
		while (T[j] != null) 
			j = h(x, ++i);
		
		T[j] = x;
		nElements++;
		
	}
	public boolean contains(Object x) {
		
		int i = 0, j = h(x,i);
		
		while (T[j] != null && ! T[j].equals(x)) 
			j = h(x, ++i);
		
		return T[j] != null;
		
	}
	
	public String toString() {
		
		boolean first = true;
		StringBuffer sb = new StringBuffer("[");
		
		for (int i = 0; i < T.length; i++)
			if (T[i] != null) {
				if (first) first = false;
				else sb.append(",");
				sb.append(T[i]);
			}
		
		sb.append("]");
		
		return sb.toString();
		
	}
	
	private void grow() {
		
		Object oldt[] = T;
		T = new Object[2 * oldt.length];
		nElements = 0;
		
		for (int i = 0; i < oldt.length; i++)
			if (oldt[i] != null)
				insert(oldt[i]);
		
	}
	public static void main(String args[]) {
		
		HashTableSet s1 = new HashTableSet(10);
		
		for (int i = 0; i < 10; i++)
			s1.insert(i + 1);
		
		System.out.println(s1);
		
	}
}

Comentários