java 基础知识

it2022-05-08  7

说说Hashtable与HashMap的区别(源代码级别)

1.最明显的区别在于Hashtable 是同步的(每个方法都是synchronized),而HashMap则不是.2.HashMap继承至AbstractMap,Hashtable继承至Dictionary ,前者为Map的骨干, 其内部已经实现了Map所需 要做的大部分工作, 它的子类只需要实现它的少量方法即可具有Map的多项特性。而后者内部都为抽象方法,需要它的实现类一一作自己的实现,且该类已过时3.两者检测是否含有key时,hash算法不一致,HashMap内部需要将key的hash码重新计算一边再检测,而 Hashtable则直接利用key本身的hash码来做验证。HashMap:

 

public V get(Object key) { if (key == null) return getForNullKey(); int hash = hash(key.hashCode()); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) return e.value; } return null; }

 

Hashtable:

 

public synchronized V get(Object key) { Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return e.value; } } return null; }

 

4.两者初始化容量大小不一致

HashTable

 

protected void rehash() { int oldCapacity = table.length; Entry[] oldMap = table; int newCapacity = oldCapacity * 2 + 1; Entry[] newMap = new Entry[newCapacity]; modCount++; threshold = (int)(newCapacity * loadFactor); table = newMap; for (int i = oldCapacity ; i-- > 0 ;) { for (Entry<K,V> old = oldMap[i] ; old != null ; ) { Entry<K,V> e = old; old = old.next; int index = (e.hash & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } }

 

Hashmap

 

void addEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); if (size++ >= threshold) resize(2 * table.length); }

 

String,StringBuffer, StringBuilder 的区别是什么?String为什么是不可变的?

String的操作都是改变赋值地址而不是改变值操作,StringBuffer与StringBuilder的区别主要是前者是线程安全的,就是说它是同步的;后者不安全,不是同步的,其它的区别不大。当你的程序不需要线程同步,一般都用StringBuilder.

Stringuilder

 

 public AbstractStringBuilder append(String str) { if (str == null) str = "null";        int len = str.length(); if (len == 0) return this; int newCount = count + len; if (newCount > value.length)     expandCapacity(newCount); str.getChars(0, len, value, count); count = newCount; return this;    }

 

 

 

 

 

 

 

cookie 和session 的区别:

 

1、cookie数据存放在客户的浏览器上,session数据放在服务器上。

 

2、cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗   考虑到安全应当使用session

 

3、session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能   考虑到减轻服务器性能方面,应当使用COOKIE

 

4、单个cookie在客户端的限制是3K,就是说一个站点在客户端存放的COOKIE不能3K.

Servlet的生命周期

Servlet被服务器实例化后,容器运行其init方法,请求到达时运行其service方法,service方法自动派遣运行与请求对应的doXXX方法(doGet,doPost)等,当服务器决定将实例销毁的时候调用其destroy方法。

http://gogole.iteye.com/blog/703954

转载于:https://www.cnblogs.com/chenyao/archive/2013/06/14/3135666.html


最新回复(0)