Java集合介绍
Collections framework概述
所有抽象出来的数据结构和操作统称为Collections framework 框架。Java程序员不必考虑数据结构的算法细节,只需要定义具体应用的数据结构实体。数据结构上的方法也用不着程序员去写,用系统的方法就行了,系统的方法总比一般程序员编写的要快。
Collection是集合接口
Collections是集合类
Set 无序,不允许重复
List 有序,可以有重复元素
ArrayList非常象Vector,它实现了可变长的数组(不推荐使用)。而LinkedList 则有些不同,它是List的链表实现。
LinkedList 可以成为堆栈,队列或者双向链表。
SetExample.java
importjava.util.HashSet;
importjava.util.Set;

publicclassSetExample

...{
publicstaticvoidmain(Stringargs[])

...{
Setset=newHashSet();
set.add("one");
set.add("second");
set.add("3rd");
set.add(newInteger(4));
set.add(newFloat(5.0F));
set.add("second");//duplicate,notadded
set.add(newInteger(4));//duplicate,notadded
System.out.println(set);
}
}
输出:one, 4, 5.0, 3rd, second
ListExample.java
importjava.util.ArrayList;
importjava.util.List;


/***//**
*@author罗锋,创建时间Feb5,2007
*/
publicclassListExample

...{

/***//**
*@paramargs
*/
publicstaticvoidmain(String[]args)

...{
Listlist=newArrayList();
list.add("one");
list.add("second");
list.add("3rd");
list.add(newInteger(4));
list.add(newFloat(5.0F));
list.add("second");//duplicate,isadded
list.add(newInteger(4));//duplicate,isadded
System.out.println(list);
}
}
输出:one, second, 3rd, 4, 5.0, second, 4
Iterators迭代器
Iteration是获取集合中元素的过程
An Iterator of a Set is unordered.
A ListIterator of a List can be scanned
forwards(using the next method) or backwards(using the previous method);
List list = new ArrayList();
Iterator elements = list.iterator();
while(elements.hasNext())
{
System.out.println(elements.next());
}
Map接口,HashMap类
Map接口是Dictionary类的替代品。
HashMap是以哈希表的形式存储键值对,速度快。
Collections in JDK 1.1
Vector : implements the List interface.
Stack : is a subclass of Vector and supports the push , pop, and peek methods.
HashTable : implements the Map interface.
Enumeration : is a variation on the Iterator interface, An enumeration is returned by the elements method in Vector, Stack ,and Hashtable
这些类是线程安全的,因此是重量级的。
Properities类
哈希表里存的关键字值对可以是各种类型。而propeities就相对简单多了。它只存放字符串对。
propeities用setProperty和getProperty来处理值,此类的值只能是String
System Properities Example
importjava.util.Enumeration;
importjava.util.Properties;

/***//**
*@author罗锋,创建时间Feb6,2007
*/
publicclassPropertiesExample

...{

/***//**
*@paramargs
*/
publicstaticvoidmain(String[]args)

...{
Propertiesprops=System.getProperties();
Enumerationprop_names=props.propertyNames();
while(prop_names.hasMoreElements())

...{
Stringprop_name=(String)prop_names.nextElement();
Stringproperty=props.getProperty(prop_name);
System.out.println("property"+prop_name+"is"+property+"");
}
}
}
本文地址:
http://www.45fan.com/dnjc/70210.html