1、 总体诉说:sql
1.ArrayList是不固定的,好比用sql查询数据库,不知道有多少记录返回,用Arraylist。 数据库
2.HashMap/Hashtable 和 Vector/ArrayList 都是放一组对象,一个是用key object来定位element, 另外一个是用index定位element. api
3.ArrayList 是一维的,HashTable、HashMap都是二维的。 数组
4.HashMap的同步问题可经过Collections的一个静态方法获得解决:Map Collections.synchronizedMap(Map m);使用以下:Map map=Collections.synchronizedMap(new HashMap())。这个方法返回一个同步的Map,这个Map封装了底层的HashMap的全部方法,使得底层的HashMap即便是在多线程的环境中也是安全的。 安全
5.在HashMap中,null能够做为键,这样的键只有一个;能够有一个或多个键所对应的值为null。当get()方法返回null值时,便可以表示HashMap中没有该键,也能够表示该键所对应的值为null。所以,在HashMap中不能由get()方法来判断HashMap中是否存在某个键,而应该用containsKey()方法来判断多线程
2、从代码级别说明spa
2.1. 可储存的值线程
//数组 => 可存储基础数据类型或者对象对象
- int[] data = {1,2,3,4,5};
- String[] name = {"Mike","Tom","Jessie"};
//ArrayList => 只可存储对象ci
- ArrayList nameList = new ArrayList();
- nameList.add(new String("Ada"));
※可是如下代码编译器不会报错:
- ArrayList numberList = new ArrayList();
- numberList.add(100); //虽然看上去是存的基础数据类型,但实际上被强制转换为Object对象
//HashMap => 只可存储成对的对象
- HashMap capitalCityMap = new HashMap();
- capitalCityMap.put("China","Beijing");
※可是如下代码编译器不会报错:
- HashMap capitalCityMap2 = new HashMap();
- capitalCityMap2.put(1,"Beijing"); //虽然看上去是存的基础数据类型,但实际上被强制转换为Object对象
2.二、如何取得元素个数
//数组
- int[] data = {1,2,3,4,5};
- int size1 = data.length;
//ArrayList
- ArrayList nameList = new ArrayList();
- nameList.add(new String("Ada"));
- int size2 = nameList.size();
//HashMap
- HashMap capitalCityMap = new HashMap();
- capitalCityMap.put("China","Beijing");
- int size3 = capitalCityMap.size();
2.3 是否容许重复值
//数组
- int[] data = {1,1,1,1,1}; //OK
//ArrayList
- ArrayList nameList = new ArrayList();
- nameList.add(new String("Ada"));
- nameList.add(new String("Ada")); //OK
//HashMap
- HashMap capitalCityMap = new HashMap();
- capitalCityMap.put("China","Beijing");
- capitalCityMap.put("China","Shanghai");//OK,可是"China"这个Key关联的Value就会被覆盖,
- //也就是"China"对应的对象再也不是"Beijing",而是"Shanghai"
2.4 如何遍历
//数组
- int[] data = {1,1,1,1,1}; //OK
- for(int i=0;i<data.length;i++){
- System.out.println(data[i]);//经过数组下标进行遍历
- }
//ArrayList
- ArrayList nameList = new ArrayList();
- nameList.add(new String("Ada"));
- Iterator iter = nameList.iterator();
- while(iter.hasNext()){
- String name = (String)iter.next();
- System.out.println(name);//经过迭代器Iterator进行遍历
- }
//或者
- for(int i=0;i<nameList.size();i++){
- System.out.println(nameList.get(i));
- }
// HashMap
- HashMap capitalCityMap = new HashMap();
- capitalCityMap.put("China","Beijing");
- Iterator iter2 = capitalCityMap.entrySet().iterator();
- while(iter2.hasNext()){
- Map.Entry cityAndCountry = (Map.Entry)iter2.next();
- String country = (String)cityAndCountry.getKey();
- String city = (String)cityAndCountry.getValue();
- System.out.println(country + "'s capital city is " + city);//经过迭代器Iterator进行遍历
- }