UnsortedHashSet.java 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import java.util.LinkedList;
  2. import java.lang.reflect.Array;
  3. public class UnsortedHashSet<E> {
  4. private static final double LOAD_FACTOR_LIMIT = 0.7;
  5. private int size;
  6. private LinkedList<E>[] con;
  7. public UnsortedHashSet() {
  8. con = (LinkedList<E>[])(new LinkedList[10]);
  9. }
  10. public boolean add(E obj) {
  11. int oldSize = size;
  12. int index = Math.abs(obj.hashCode()) % con.length;
  13. if(con[index] == null)
  14. con[index] = new LinkedList<E>();
  15. if(!con[index].contains(obj)) {
  16. con[index].add(obj);
  17. size++;
  18. }
  19. if(1.0 * size / con.length > LOAD_FACTOR_LIMIT)
  20. resize();
  21. return oldSize != size;
  22. }
  23. private void resize() {
  24. UnsortedHashSet<E> temp = new UnsortedHashSet<E>();
  25. temp.con = (LinkedList<E>[])(new LinkedList[con.length * 2 + 1]);
  26. for(int i = 0; i < con.length; i++){
  27. if(con[i] != null)
  28. for(E e : con[i])
  29. temp.add(e);
  30. }
  31. con = temp.con;
  32. }
  33. public int size() {
  34. return size;
  35. }
  36. }