java HashTable哈希表 及 映射 示例

xiaoxiao2021-02-28  154

有一种数据结构,可以快速查找所需要的对象,这就是散列表(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.01.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) 获取与键对应的值;返回与键对应的对象
转载请注明原文地址: https://www.6miu.com/read-24841.html

最新回复(0)