散列表

Posted on

散列表

博客分类:

【散列表】 它是用一个散列函数把关键字 映射到散列表中的特定位置。 在理想情况下,如果元素e 的关键字为k,散列函 数为f,那么e 在散列表中的位置为f (k)。要搜索关键字为k 的元素,首先要计算出f (k),然后看 表中f (k)处是否有元素。如果有,便找到了该元素。如果没有,说明该字典中不包含该元素。 在前一种情况中,如果要删除该元素,只需把表中f (k)位置置为空即可。在后一种情况中,可 以通过把元素放在f (k)位置以实现插入。 此例是一个理想情况下的散列表,不考虑关键字重复的情况

Java代码 收藏代码

  1. public class HashList {
  2. private String[] table;
  3. private int size;
  4. private int threshold;
  5. private static final int INITIAL_CAPACITY = 10;
  6. private static final int SIZE_INCREASE = 10;
  7. private static final float DEFAULT_LOAD_FACTOR = 0.75f;
  8. public HashList(){
  9. threshold = (int)(INITIAL_CAPACITY/*DEFAULT_LOAD_FACTOR);
  10. table = new String[INITIAL_CAPACITY];
  11. }
  12. public HashList(String[] table){
  13. this.table = table;
  14. }
  15. ///
  16. /* Get the actual size of the list
  17. /* @return
  18. /*/
  19. public int size(){
  20. return size;
  21. }
  22. ///
  23. /* for test
  24. /* @return
  25. /*/
  26. public String[] getElements(){
  27. return table;
  28. }
  29. public boolean contains(String element) {
  30. if (element == null) {
  31. return false;
  32. }
  33. if (element.equals(table[getIndex(element)])) {
  34. return true;
  35. }
  36. return false;
  37. }
  38. public void add(String element){
  39. int index = getIndex(element);
  40. if(size>threshold){
  41. resize();
  42. }
  43. table[index] = element;
  44. size++;
  45. }
  46. //private methods
  47. ///
  48. /* resize the array
  49. /*/
  50. private void resize(){
  51. String[] newArray = new String[table.length+SIZE_INCREASE];
  52. for(int i=0;i<table.length;i++){
  53. newArray[i] = table[i];
  54. }
  55. table = newArray;
  56. threshold = (int)(table.length/*DEFAULT_LOAD_FACTOR);
  57. }
  58. ///
  59. /* get the index of the element
  60. /* @param element
  61. /* @return
  62. /*/
  63. public int getIndex(String element) {
  64. return (element.hashCode() & 0x7FFFFFFF) % table.length;
  65. }
  66. }

来源: [http://tangyanbo.iteye.com/blog/1476372](http://tangyanbo.iteye.com/blog/1476372)

希望本站内容对您有点用处,有什么疑问或建议请在后面留言评论
转载请注明作者(RobinChia)和出处 It so life ,请勿用于任何商业用途
本文链接: 散列表