ASP自定义HashTable类

ASP中有dictionary对象,类似哈希表的键值对,这样的键值对可以用在很多地方,可惜的是dictionary本身有很多不足之处,当我发现我无法将它使用的灵活时,我想到不如用数组自定义一个hash结构,记得以前曾写过一个arraylist的asp封装,于是有了本文的HashTable。

  1. <%  
  2. Class HashTable  
  3. '// Code By Shaoyun  
  4. '// Date:2009-7-9 11:46:14  
  5. '// Site:Devjs.com  
  6. Private m_keys,m_vals,m_cnt,m_repeat  
  7.  
  8. Private Sub Class_Initialize()  
  9.     m_keys=array()  
  10.     m_vals=array()  
  11.     m_cnt=0  
  12.     m_repeat=false  
  13. End Sub 
  14.  
  15. Private Sub Class_Terminate()  
  16. End Sub 
  17.  
  18. ' 是否允许键名重复  
  19. Public Property Let Repeat(boolval)  
  20.     m_repeat=boolval  
  21. End Property 
  22.  
  23. ' 获取键值对的总数  
  24. Public Property Get Count()  
  25.     Count=m_cnt  
  26. End Property 
  27.  
  28. ' 获取键值  
  29. Public Default Property Get Keys(keyname)  
  30.     dim i  
  31.     for i=0 to m_cnt-1  
  32.         if keyname=m_keys(i) then Keys=m_vals(i)  
  33.     next  
  34. End Property 
  35.  
  36. ' 添加键值  
  37. Public Sub Add(key,val)  
  38.     dim done  
  39.     done=false  
  40.     If m_repeat Then 
  41.         done=true  
  42.     else  
  43.         if Not Exist(key) then done=true  
  44.     End If 
  45.     If done Then 
  46.         Redim Preserve m_keys(m_cnt)  
  47.         Redim Preserve m_vals(m_cnt)  
  48.         m_keys(m_cnt)=key  
  49.         m_vals(m_cnt)=val  
  50.         m_cnt=m_cnt+1  
  51.     end if  
  52. End Sub 
  53.  
  54. ' 检测键是否存在  
  55. Public Function Exist(keyname)  
  56.     Exist=false  
  57.     dim i  
  58.     for i=0 to m_cnt-1  
  59.         if keyname=m_keys(i) then  
  60.             Exist=true  
  61.             Exit For 
  62.         end if  
  63.     next  
  64. End Function 
  65.  
  66. ' 导出数据  
  67. Public function Dump()  
  68.     dim i,ostr  
  69.     for i= 0 to m_cnt-1  
  70.         ostr=ostr & "Array(""" & m_keys(i) & """," & m_vals(i) & ")," 
  71.     next  
  72.     if m_cnt>0 then ostr=mid(ostr,1,len(ostr)-1)  
  73.     Dump = "Array(" & ostr & ")" 
  74. End function  
  75.  
  76. ' 通过数组赋值  
  77. ' 数组传值约定:array(array("item1",1),array("item2",2))  
  78. Public Sub AssignByArray(ary)  
  79.     dim i  
  80.     for i=0 to ubound(ary)  
  81.         if IsArray(ary(i)) Then 
  82.             Add ary(i)(0),ary(i)(1)  
  83.         end if  
  84.     next  
  85. End Sub 
  86. End Class 
  87.  
  88. ' 使用实例  
  89. set ht=new HashTable  
  90. ht.add "haha",2  
  91. ht.add "wawa",4  
  92. ht.add "xixi",3  
  93. ht.add "xixi",6  
  94. ht.AssignByArray(array(array("a",1),array("b",2)))  
  95. Response.Write ht.dump  
  96. Response.Write ht.count  
  97. Response.Write ht("haha")  
  98. set ht=nothing  
  99. %> 

将以前写的arraylist链接贴在后面,都是为了用着方便,没什么难度。

ASP自定义ArrayList类
链接地址:http://www.devjs.com/Article/25.aspx
posted @ 2009-07-09 11:32  shaoyun  阅读(340)  评论(0编辑  收藏  举报