Chinaunix首页 | 论坛 | 博客
  • 博客访问: 151495
  • 博文数量: 15
  • 博客积分: 2061
  • 博客等级: 大尉
  • 技术积分: 395
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-06 14:25
文章分类

全部博文(15)

文章存档

2020年(1)

2012年(1)

2009年(7)

2008年(6)

我的朋友

分类: Java

2008-09-25 11:22:35

JAVA的容器---List,Map,Set
Collection
├List
│├LinkedList
│├ArrayList
│└Vector
 └Stack
└Set
Map
├Hashtable
├HashMap
└WeakHashMap

Collection接口
  Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements)。一些 Collection允许相同的元素而另一些不行。一些能排序而另一些不行。Java SDK不提供直接继承自Collection的类,Java SDK提供的类都是继承自Collection子接口ListSet
  所有实现Collection接口的类都必须提供两个标准的构造函数:无参数的构造函数用于创建一个空的Collection,有一个 Collection参数的构造函数用于创建一个新的Collection,这个新的Collection与传入的Collection有相同的元素。后一个构造函数允许用户复制一个Collection
  如何遍历Collection中的每一个元素?不论Collection的实际类型如何,它都支持一个iterator()的方法,该方法返回一个迭代子,使用该迭代子即可逐一访问Collection中每一个元素。典型的用法如下:
    Iterator it = collection.iterator(); // 获得一个迭代子
    while(it.hasNext()) {
      Object obj = it.next(); // 得到下一个元素
    }
  由Collection接口派生的两个接口是ListSet

List接口
  List是有序的Collection,使用此接口能够精确的控制每个元素插入的位置。用户能够使用索引(元素在List中的位置,类似于数组下标)来访问List中的元素,这类似于Java的数组。
和下面要提到的Set不同,List允许有相同的元素。
  除了具有Collection接口必备的iterator()方法外,List还提供一个listIterator()方法,返回一个 ListIterator接口,和标准的Iterator接口相比,ListIterator多了一些add()之类的方法,允许添加,删除,设定元素,还能向前或向后遍历。
  实现List接口的常用类有LinkedListArrayListVectorStack

LinkedList
  LinkedList实现了List接口,允许null元素。此外LinkedList提供额外的getremoveinsert方法在 LinkedList的首部或尾部。这些操作使LinkedList可被用作堆栈(stack),队列(queue)或双向队列(deque)。
  注意LinkedList没有同步方法。如果多个线程同时访问一个List,则必须自己实现访问同步。一种解决方法是在创建List时构造一个同步的List
    List list = Collections.synchronizedList(new LinkedList(...));

ArrayList
  ArrayList实现了可变大小的数组。它允许所有元素,包括nullArrayList没有同步。
size
isEmptygetset方法运行时间为常数。但是add方法开销为分摊的常数,添加n个元素需要O(n)的时间。其他的方法运行时间为线性。
  每个ArrayList实例都有一个容量(Capacity),即用于存储元素的数组的大小。这个容量可随着不断添加新元素而自动增加,但是增长算法并没有定义。当需要插入大量元素时,在插入前可以调用ensureCapacity方法来增加ArrayList的容量以提高插入效率。
  和LinkedList一样,ArrayList也是非同步的(unsynchronized)。

Vector
  Vector非常类似ArrayList,但是Vector是同步的。由Vector创建的Iterator,虽然和ArrayList创建的 Iterator是同一接口,但是,因为Vector是同步的,当一个Iterator被创建而且正在被使用,另一个线程改变了Vector的状态(例如,添加或删除了一些元素),这时调用Iterator的方法时将抛出ConcurrentModificationException,因此必须捕获该异常。

Stack
  Stack继承自Vector,实现一个后进先出的堆栈。Stack提供5个额外的方法使得Vector得以被当作堆栈使用。基本的pushpop 方法,还有peek方法得到栈顶的元素,empty方法测试堆栈是否为空,search方法检测一个元素在堆栈中的位置。Stack刚创建后是空栈。

Set接口
  Set是一种不包含重复的元素的Collection,即任意的两个元素e1e2都有e1.equals(e2)=falseSet最多有一个null元素。
  很明显,Set的构造函数有一个约束条件,传入的Collection参数不能包含重复的元素。
  请注意:必须小心操作可变对象(Mutable Object)。如果一个Set中的可变元素改变了自身状态导致Object.equals(Object)=true将导致一些问题。

Map接口
  请注意,Map没有继承Collection接口,Map提供keyvalue的映射。一个Map中不能包含相同的key,每个key只能映射一个 valueMap接口提供3种集合的视图,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射。

Hashtable
  Hashtable继承Map接口,实现一个key-value映射的哈希表。任何非空(non-null)的对象都可作为key或者value
  添加数据使用put(key, value),取出数据使用get(key),这两个基本操作的时间开销为常数。
Hashtable
通过initial capacityload factor两个参数调整性能。通常缺省的load factor 0.75较好地实现了时间和空间的均衡。增大load factor可以节省空间但相应的查找时间将增大,这会影响像getput这样的操作。
使用Hashtable的简单示例如下,将123放到Hashtable中,他们的key分别是”one””two””three”
    Hashtable numbers = new Hashtable();
    numbers.put(“one”, new Integer(1));
    numbers.put(“two”, new Integer(2));
    numbers.put(“three”, new Integer(3));
  要取出一个数,比如2,用相应的key
    Integer n = (Integer)numbers.get(“two”);
    System.out.println(“two = ” + n);
  由于作为key的对象将通过计算其散列函数来确定与之对应的value的位置,因此任何作为key的对象都必须实现hashCodeequals方法。hashCodeequals方法继承自根类Object,如果你用自定义的类当作key的话,要相当小心,按照散列函数的定义,如果两个对象相同,即obj1.equals(obj2)=true,则它们的hashCode必须相同,但如果两个对象不同,则它们的hashCode不一定不同,如果两个不同对象的hashCode相同,这种现象称为冲突,冲突会导致操作哈希表的时间开销增大,所以尽量定义好的hashCode()方法,能加快哈希表的操作。
  如果相同的对象有不同的hashCode,对哈希表的操作会出现意想不到的结果(期待的get方法返回null),要避免这种问题,只需要牢记一条:要同时复写equals方法和hashCode方法,而不要只写其中一个。
  Hashtable是同步的。

HashMap
  HashMapHashtable类似,不同之处在于HashMap是非同步的,并且允许null,即null valuenull key。,但是将HashMap视为Collection时(values()方法可返回Collection),其迭代子操作时间开销和HashMap 的容量成比例。因此,如果迭代操作的性能相当重要的话,不要将HashMap的初始化容量设得过高,或者load factor过低。

WeakHashMap
  WeakHashMap是一种改进的HashMap,它对key实行弱引用,如果一个key不再被外部所引用,那么该key可以被GC回收。

总结
  如果涉及到堆栈,队列等操作,应该考虑用List,对于需要快速插入,删除元素,应该使用LinkedList,如果需要快速随机访问元素,应该使用ArrayList
  如果程序在单线程环境中,或者访问仅仅在一个线程中进行,考虑非同步的类,其效率较高,如果多个线程可能同时操作一个类,应该使用同步的类。
  要特别注意对哈希表的操作,作为key的对象要正确复写equalshashCode方法。
  尽量返回接口而非实际的类型,如返回List而非ArrayList,这样如果以后需要将ArrayList换成LinkedList时,客户端代码不用改变。这就是针对抽象编程。



示例代码:

//ArrayList
{
ArrayList arraylist=new ArrayList();
arraylist.add(0,"end");//指定索引加入值
//需注意的是,如果现有2个值,我加入索引为5的那么就会出现异常
for(int i=0;i<2;i++){
arraylist.add(i,String.valueOf(i));
}
System.out.println("ArrayList:");
for(int i=0;i System.out.print(arraylist.get(i)+";");
}
arraylist.add("0");//直接加入值到ArrayList的最后
arraylist.add("0");
System.out.print("\nArrayList\'s lastIndexOf(\"0\") is "+arraylist.lastIndexOf("0"));
}
//Arrays
{
String []array=new String[]{"a","b","c"};
List list=Arrays.asList(array);
System.out.println("\nArrays:");
for(int i=0;i System.out.print(list.get(i)+";");
}
System.out.print("\nArrays\'s length is "+array.length);//打印数组的长度
}
//Collections
{
String []array=new String[]{"a","b","c"};
List list=Arrays.asList(array);
Collections.fill(list,"Fill");//用Fill填充全部元素
System.out.println("\nCollections:");
for(int i=0;i System.out.print(list.get(i)+";");
}
array=new String[]{"1","2","3"};
List list2=Arrays.asList(array);
Collections.copy(list,list2);//拷贝list2的数据进list
System.out.println("\n"+list);
Collections.swap(list,2,1);//调换索引为1和2的元素的位置
System.out.println(list);
}
//EventObject
{
String s="hello";
String s2=s;
EventObject eventobject=new EventObject(s);//一个准容器类型,确切的归类它不是容器
System.out.println("EventObject:");
System.out.println(eventobject.getSource());
System.out.println(eventobject.equals(s2));
}
//HashMap
{
HashMap hashmap=new HashMap();//一个速度最快的容器
hashmap.put("0","c");
hashmap.put("1","a");
hashmap.put("2","b");
hashmap.put("3","a");
System.out.println("HashMap:");
System.out.println(hashmap);//该容器有其内部的排序方式
Set set=hashmap.keySet();//获取全部键
Iterator iterator=set.iterator();
while(iterator.hasNext()){
System.out.print(hashmap.get(iterator.next())+";");
}
}
//HashSet
{
HashSet hashset=new HashSet();//一个绝对不能重复的类型
hashset.add("c");
hashset.add("b");
hashset.add("a");
hashset.add("a");
hashset.add("b");
System.out.println("\nHashSet:");
System.out.println(hashset);
Iterator iterator=hashset.iterator();//取出元素
while(iterator.hasNext()){
System.out.print(iterator.next()+";");
}
}
//Hashtable
{
Hashtable hashtable=new Hashtable();//一个完全可以由其他容器替换的老容器类型
hashtable.put("0","c");
hashtable.put("1","a");
hashtable.put("3","c");
hashtable.put("2","b");
System.out.println("\nHashtable:");
Enumeration enumeration=hashtable.elements();//获取元素,Enumeration已经不是主流,Iterator是它的下一代替代品
while(enumeration.hasMoreElements()){
System.out.print(enumeration.nextElement()+";");
}
}
//IdentityHashMap
{
IdentityHashMap identityhashmap=new IdentityHashMap();
identityhashmap.put("0","c");
identityhashmap.put("1","a");
identityhashmap.put("3","b");
identityhashmap.put("2","a");
System.out.println("\nIdentityHashMap:");
System.out.println(identityhashmap);
System.out.println(identityhashmap.containsKey("3"));//是否包含这个键
System.out.println(identityhashmap.containsValue("a"));//是否包含值
Set set=identityhashmap.entrySet();//传为Set类型
System.out.println(set);
set=identityhashmap.keySet();//全部键
System.out.println(set);
}
//LinkedHashMap
{
LinkedHashMap linkedhashmap=new LinkedHashMap();
linkedhashmap.put("0","b");
linkedhashmap.put("2","a");
linkedhashmap.put("1","c");
linkedhashmap.put("3","b");
System.out.println("LinkedHashMap:");
System.out.println(linkedhashmap);
System.out.println(linkedhashmap.containsKey("2"));//是否包含这个键
System.out.println(linkedhashmap.containsValue("c"));//是否包含值
Set set=linkedhashmap.keySet();
Iterator iterator=set.iterator();
while(iterator.hasNext()){
System.out.print(linkedhashmap.get(iterator.next())+";");
}
}
//LinkedHashSet
{
LinkedHashSet linkedhashset=new LinkedHashSet();//它包含了几种Set的属性但却没有自己的特色
linkedhashset.add("c");
linkedhashset.add("a");
linkedhashset.add("a");
linkedhashset.add("b");
System.out.println("\nLinkedHashSet:");
System.out.println(linkedhashset);
System.out.println(linkedhashset.contains("a"));//是否包含对象
Iterator iterator=linkedhashset.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+";");
}
}
//LinkedList
{
LinkedList linkedlist=new LinkedList();//自由使用是它的特色
linkedlist.add("a");
linkedlist.add(1,"c");
linkedlist.addLast("b");
linkedlist.addFirst("d");
System.out.println("\nLinkedList:");
System.out.println(linkedlist);
//linkedlist.clear();//该方法清空容器
//linkedlist.remove(0);//删除索引为0的元素
//linkedlist.remove("d");//删除值为d的元素
//linkedlist.removeFirst();//删除第一个元素
//linkedlist.removeLast();//删除最后一个元素
for(int i=0;i System.out.print(linkedlist.get(i)+";");
}
}
//Stack
{
Stack stack=new Stack();//堆栈
stack.add("b");
stack.add(0,"c");
stack.push("d");
stack.add("e");
stack.push("a");
Enumeration enumeration=stack.elements();
System.out.println("\nStack:");
while(enumeration.hasMoreElements()){
System.out.print(enumeration.nextElement()+";");
}
//后进先出
System.out.println("\n"+stack.peek());
System.out.println(stack.pop());
System.out.println(stack.contains("d")+";"+stack.contains("a"));//是否包含该元素,有趣的事情发生了
System.out.println(stack.search("c"));//非常有用的属性,检索,但是由后向前的排列
}
//TreeMap
{
TreeMap treemap=new TreeMap();
treemap.put("0","d");
treemap.put("2","a");
treemap.put("1","b");
treemap.put("3","c");
System.out.println("\nTreeMap:");//可以对键排序
System.out.println(treemap);
System.out.println(treemap.firstKey());//返回第一个键
Set set=treemap.keySet();
Iterator iterator=set.iterator();
while(iterator.hasNext()){
System.out.print(treemap.get(iterator.next())+";");
}
}
//TreeSet
{
TreeSet treeset=new TreeSet();//自动排序内容
treeset.add("b");
treeset.add("a");
treeset.add("c");
treeset.add("d");
System.out.println("\nTreeSet:");
System.out.println(treeset);
System.out.println(treeset.first());//返回第一个元素
Iterator iterator=treeset.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+";");
}
}
//Vector
{
Vector vector=new Vector();
vector.add(0,"b");
vector.add("a");
vector.addElement("d");
vector.add("c");
System.out.println("\nVector:");
System.out.println(vector);
vector.set(2,"h");//替换掉指定索引的元素
System.out.println(vector);
Object []str=vector.toArray();
for(int i=0;i System.out.print(str[i]+";");
}
vector.setSize(2);//重新设置大小为2
System.out.println("\n"+vector);
}
//WeakHashMap
{
WeakHashMap weakhashmap=new WeakHashMap();
weakhashmap.put("1","b");
weakhashmap.put("2","c");
weakhashmap.put("0","d");
weakhashmap.put("3","a");
System.out.println("\nWeakHashMap:");
System.out.println(weakhashmap);
System.out.println(weakhashmap.containsKey("3"));//是否包含键
System.out.println(weakhashmap.containsValue("d"));//是否包含值
Set set=weakhashmap.entrySet();
Iterator iterator=set.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+";");
}
//weakhashmap.remove("2");//删除该键对应的值
//weakhashmap.get("1");//获取指定键的值
}
}








阅读(1204) | 评论(0) | 转发(0) |
0

上一篇:eclipse导入项目

下一篇:java 判断是否数字

给主人留下些什么吧!~~