java提供了大量持有对象的方式:
(1)数组将数字与对象联系起来。它保存类型明确的对象,查询对象时,不需要对结果做类型的转换。它可以是多维的,可以保存基本类型的数据。但是,数组一旦生成,其容量就不能改变,即不能动态改变数组的大小。
(2)Collection保存单一的元素,而Map保存相关联的键值对(key, value)。有了java的泛型,你就可以指定容器中存放的对象类型,因此你就不会将错误的对象放置到容器中,并且在容器中获取元素时,不用进行类型的转换。各种Collection和Map都可以在你向其中添加更多元素的时候自动调整其尺寸。容器不能持有基本类型,但是自动包装机制会仔细地执行基本类型到容器中持有的包装器类型之间的双向转换。
//加泛型
Collection<T> collction = new ArrayList<T>()
(3)像数组一样,List也建立数字索引与对象的关联,因此,数组和List都是排好序的容器。但List能自动扩充容量、
(4)如果要进行大量的随机访问,则采用ArrayList。
ArrayList<Dog> dog = new ArrayList<Dog>();
for(int i = 0; i < 5; i++){
dog.add(new Dog())
}
for(int j = 0; j< dog.size(); j++){
Dog d = dog.get(j);
}
如果要经常从List中插入或者删除元素,则采用LinkedList。
(5)Map是一种将对象(而非数字)与对象关联的设计。HashMap设计用来快速访问,而TreeMap保持键始终处于排序状态,所以没有HashMap快(按字母顺序排序)。LInkedHashMap保持元素插入的顺序,但是也提供了快速访问的能力。
(6)Set不接受重复元素。HashSet提供最快的查询速度,而TreeSet保持元素处于排序状态,LinkedHashSet以插入顺序保存元素。
(7 )HashMap和HashTable的区别:HashTable是同步的,这个类中的一些方法保证了HashTable中的对象时线程安全的,而HashMap是异步的,同步会影响执行的效率;HashMap可将空值作为key和value,但是HashTable是不能放入空值的。
(8)ArrayList和Vector的区别: vector是同步的,ArrayList是异步的。从内部原理来讲,ArrayList和Vector都是使用数组Array来控制集合中的对象,当你向两种集合中添加元素的时候,如果数目超过了内部数组的长度,他们都需要扩展内部数组的长度,Vector缺省的情况下缺省情况下增长一倍,ArrayList增长50%。
(9)在新程序中不应该使用过时Vector、HashTable和Stack。
package com.collect;
import java.util.*;
public class Demo1 {
static Collection fill(Collection<String> collection){
collection.add("cat");
collection.add("rat");
collection.add("dog");
collection.add("dog");
return collection;
}
static Map fill(Map<String, String> map){
map.put("cat", "1");
map.put("rat", "2");
map.put("dog", "3");
map.put("dog", "4");
return map;
}
public static void main(String[] args){
System.out.println(fill(new ArrayList<String>()));
System.out.println(fill(new LinkedList<String>()));
System.out.println(fill(new HashSet<String>()));
System.out.println(fill(new TreeSet<String>()));
System.out.println(fill(new LinkedHashSet<String>()));
System.out.println(fill(new HashMap<String,String>()));
System.out.println(fill(new TreeMap<String, String>()));
System.out.println(fill(new LinkedHashMap<String, String>()));
}
}