java HashTable 雜湊表 及 對映 示例
阿新 • • 發佈:2019-01-01
有一種資料結構,可以快速查詢所需要的物件,這就是散列表(hash table)
散列表為每個元素計算一個整數,稱為雜湊碼(hash code)
package NEW_DATE_SEQUENCE_PACKAGE;
import java.util.*;
/**
Iterator可用來遍歷Set和List集合,但是ListIterator只能用來遍歷List。
Iterator對集合只能是前向遍歷,ListIterator既可以前向也可以後向。
ListIterator實現了Iterator介面,幷包含其他的功能,比如:增加元素,替換元素,獲取前一個和後一個元素的索引,等等。
* @author cmx
*/
public class J_8_31_3
{
public static void main(String[] args)
{
Set<String> words=new HashSet<>();
long totalTime=0;
try(Scanner in=new Scanner(System.in))
{
int j=0;
while(in.hasNext())
{
String word=in .next();
++j;
long callTime =System.currentTimeMillis();
words.add(word);
callTime=System.currentTimeMillis()-callTime;
totalTime+=callTime;
if(j>50)
break;
}
}
Iterator<String> iter=words.iterator();
System.out .println("...");
System.out.println("...");
System.out.println("...");
for(int i=0;i<20 &&iter.hasNext();++i)
{
System.out.println(iter.next());
}
System.out.println("...");
System.out.println(words.size()+"distinct words "+totalTime+" milliseconds.");
}
}
HashSet()
構造一個空散列表
HashSet(Collection<? extends E> elements)
構造一個雜湊集,將集合中的所有元素新增到這個雜湊集中。
HashSet(int initialCapacity)
構造一個空的具有指定容量的雜湊集
HashSet(int initialCapacity ,float loadFactor)
構造一個具有指定容量和裝填因子(一個0.0到1.0之間的數值,確定散列表填充的百分比,當大於這個百分比時,散列表進行再雜湊)的空雜湊集。
java.lang.Object
int hashCode()
返回這個物件的雜湊碼。雜湊碼可以是任意整數,包括正數或者負數,equals和hashCode的定義必須相容,即如果x.equals(y)為true,則x.hashCode(y)必須等於y.hashCode(x);
對映
package NEW_DATE_SEQUENCE_PACKAGE;
import java.util.*;
/**
*
* @author cmx
*/
public class J_8_31_6_map
{
public static void main(String[] args)
{
Map<String,Employee_61> staff=new HashMap<>();
staff.put("1", new Employee_61("well"));
staff.put("2", new Employee_61("hello"));
staff.put("3", new Employee_61("good"));
staff.put("4", new Employee_61("thanks"));
System.out.println(staff+"______1");
staff.remove("1");
System.out.println(staff+"______2");
staff.put("5", new Employee_61("oo"));
System.out.println(staff+"______3");
System.out.println(staff.get("1"));
staff.forEach((x,y)->System.out.println(staff.get(x)));
System.out.println(staff+"______4");
}
}
class Employee_61
{
private String name;
public Employee_61(String name)
{
this.name=name;
}
}
java.util.Map<K,V>
V get(Object key)
獲取與鍵對應的值;返回與鍵對應的物件