一、 整体诉说:
1.ArrayList是不固定的,比如用sql查询数据库,不知道有多少记录返回,用Arraylist。
2.HashMap/Hashtable 和 Vector/ArrayList 都是放一组对象,一个是用key object来定位element, 另一个是用index定位element.
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.1. 可储存的值
//数组 => 可存储基础数据类型或者对象
- int[] data = {1,2,3,4,5};
- String[] name = {"Mike","Tom","Jessie"};
//ArrayList => 只可存储对象
- 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.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进行遍历
- }