爱程序网

java 集合知识整理

来源: 阅读:

  1. java集合类图

 


 

  1. HashMap和Hashtable的区别
  HashMap HashTable
 继承方式

extends AbstractMap implements Map
extends Dictionary implements Map
线程安全 是(方法都是synchronized修饰)

效率相对比
允许有null的键和值
判断包含的方法 containsvalue和containsKey contains

hash数组默认大小

11

 

16

 

hash数组增加方式

 old*2+1

2的指数增加

 

  1. List的遍历
 1         List<String> list = new ArrayList<String>();
 2 
 3         String preString = "aa";
 4         for (int j = 0; j < 100000000; j++) {
 5             list.add(preString);
 6         }
 7 
 8         // 方法1(速度最快,List特有的)
 9         for (int i = 0, len = list.size(); i < len; i++) {
10             list.get(i);
11         }
12 
13         // 方法2 (for each-最耗时)
14         for (String tmp : list) {
15         }
16 
17         // 方法3(与方法2,4一样,适用所有实现了Iterable接口的类,常见的有:Queue,Set,Collection,List)
18         Iterator<String> iter = list.iterator();
19         while (iter.hasNext()) {
20             String str = iter.next();
21         }
22     
23         // 方法4
24         for (Iterator<String> it2 = list.iterator(); it2.hasNext();) {
25             String str = it2.next();
26         }

 

    2.map的遍历

 

 1         HashMap<Integer, String> map = new HashMap<>();
 2         String v = "value";
 3         for(int i=0;i<10000000;i++){
 4             map.put(i, v);
 5         }
 6         
 7         //方法1,
 8         Iterator<Map.Entry<Integer, String>> it1= map.entrySet().iterator();
 9         while (it1.hasNext()) {
10             Map.Entry<Integer, String> entry =it1.next();
11             int key = entry.getKey();
12             String value = entry.getValue();
13         }
14     
15         //方法2 获取map的key集合的迭代器,耗时是方法1的7倍。
16         Iterator<Integer> it2 = map.keySet().iterator();
17         while(it2.hasNext()){
18             int key = it2.next();
19             String value = map.get(key);
20         }
21     

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助