数组、ArrayList和HashMap是Java项目开发中经常用到的容器,下面对这三个容器进行一下比较。
①可储存的值
//数组 => 可存储基础数据类型或者对象
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对象
②如何取得元素个数
//数组
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();
③是否允许重复值
//数组
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"
④如何遍历
//数组
int[] data = {1,1,1,1,1}; //OK
for(int i=0;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
// 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进行遍历
}