**哈希表
優點:速度快(插入和查找)
缺點:基於數組,不能有序的遍歷
鍵值對存儲方式,通過鍵來訪問值
hashMap.put( key , value );
解決哈希衝突有兩種方法:
開放地址法
鏈地址法
線性探測屬於開放地址法
線性探測插入演示:
數組最初狀態
在這組數據中要插入83
先對要插入數據哈希化,哈希化後的數據就是數組下標,這裏哈希化後的數據是23
然後發現23已經有數據了,產生衝突,線性探測的解決方案是依次遞增,直到找到空位
**
package map;
/*
* 2017年12月19日17:04:18
*
* 哈希表
*
* 解決哈希衝突的方法爲開放地址法(線性探測)
*/
public class HashApp
{
public dataItem [] arr ;//哈希表的底層是由數組實現的
public int size ;//當前數組的最大長度
public dataItem newItem ;//新插入的節點
public int currentSize ;//當前數組有幾個元素
//初始化
public HashApp ( int maxSize )
{
arr = new dataItem [maxSize] ;
size = maxSize ;
currentSize = 0 ;
}
//哈希化
public int hash ( int value )
{
//返回哈希化後的索引下標
return value % size ;
}
//添加新數據
public void insert ( int data )
{
//如果滿了,直接返回
if ( isFull () )
{
System.out.println ( "hashmap is full" );
return ;
}
int index = hash ( data ) ;//計算哈希化後的索引
newItem = new dataItem ( data ) ;
//當前下標中元素不爲空,說明有元素了,index遞增
while ( arr [index] != null )
{
index ++ ;
index = hash(index) ;//防止index超過數組最大索引下標
}
arr [index] = newItem ;//退出循環,說明找到空位了,放進去
++ currentSize ;
}
//刪除數據
public void delete ( int data )
{
int index = hash ( data ) ;
while ( arr [index] != null )
{
if ( arr [index].getValue () == data )
{
arr [index] = null ;
return ;
}
index ++ ;
index = hash (index) ;
}
}
//查找數據
public dataItem find ( int value )
{
int index = hash ( value ) ;
while ( arr [index] != null )
{
if ( arr [index].getValue () == value )
{
return arr [index];
}
index ++ ;
index = hash (index) ;
}
return null ;
}
//判斷數組是否滿
public boolean isFull ()
{
return currentSize == size ;
}
//哈希表無法有序的遍歷!
//所以這裏遍歷只是查看一個數據的分佈情況
public void display ()
{
for ( int i = 0 ; i < arr.length ; ++i )
{
if ( arr [ i] != null)
System.out.print ( arr [i].getValue () +" ");
}
System.out.println ( );
}
}
---------------------------------------------
package map;
public class dataItem
{
private int value ;
public dataItem ( int value )
{
this.value = value ;
}
public int getValue ()
{
return value ;
}
public void setValue ( int value )
{
this.value = value ;
}
}