Java综合例题/集合框架第二版
public class Hashtable<K,V> implements Cloneable,Serializable{
/**
* 集合取空
*/
public synchronized void clear() {
Entry<?,?> tab[] = table ;
for(int index = table.length ; --index >=0 ;)
tab[index] = null ;
count = 0 ;
}
/**
* 返回原有值,如果没有就返回指定值
* @param key
* 指定的地址
* @param defaultValue
* 指定的值
* @return
* 指定值 与 原有值
*/
public synchronized V getfault(K key , V value ) {
V value1 = get(key);
return (value1==null) ? value : value1 ;
}
/**
* 如果我想知道集合是否为空 ,就用这个
* @return
* false 和 true
*
*/
public synchronized boolean isEmpty() {
return count==0 ;
}
/**
* 可以向集合添加数值 , 但不能覆盖原有数值,如果想覆盖原有数值就要调用putIfAbsent方法
* @param key
* 指定的地址号
* @param value
* 要添加的值
* @return
* 返回要添加的数值,如果指定地址存在数值,就返回原数值
*/
public synchronized V getOrDefault(K key , V value ) {
V value1 = get(key) ;
if(value1 == null)
put(key , value);
return (null==value1) ? value : value1 ;
}
/**
* 获得地址号所在的值
* @param key
* 指定的地址号
* @return
* 集合中的数值
*/
@SuppressWarnings("unchecked")
public synchronized V get(Object key) {
Entry<?,?> tab[] = table ;
int hash = key.hashCode();
int y = 0 ;
for(int g = 0 ; ; g++) {
for( ; y < tab.length ; y++ ) {
for(Entry<?,?> e = tab[y] ; e != null ; e = e.next) {
if(hash == e.hash && e.key.equals(key)) {
V value = (V)e.value ;
return value ;
}
}
if(tab[y] != null )
continue ;
}
if(g == count)
return null;
}
}
/**
* 问一下有没有这个值
* @param value
* 指定的值
* @return
* false 和 true
*/
public synchronized boolean containsValue(Object value) {
return contains(value);
}
/**
* 询问一下单位的地址号有没有
* @param key
* @return
*/
public synchronized boolean containsKey(Object key) {
Entry<?,?> tab[] = table ;
int hash = key.hashCode() ;
if(hash >= tab.length)
throw new ArrayIndexOutOfBoundsException("Cross the border : " + (tab.length-1));
int index = (hash & 0x7fffffff ) % tab.length ;
for(Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if((e.hash == hash ) && e.key.equals(key))
return true ;
}
return false ;
}
/**
* 询问一下,集合中有没有这个值
* @param value
* 指定的值
* @return
* false 和 true
*/
public synchr
Java能力提升必选,项目实战《集合框架》
于 2022-05-07 00:06:39 首次发布