Java集合

    技术2022-05-11  101

    Collections framework概述     所有抽象出来的数据结构和操作统称为Collections framework 框架。Java程序员不必考虑数据结构的算法细节,只需要定义具体应用的数据结构实体。数据结构上的方法也用不着程序员去写,用系统的方法就行了,系统的方法总比一般程序员编写的要快。  Collection是集合接口  Collections是集合类  Set    无序,不允许重复  List    有序,可以有重复元素  ArrayList非常象Vector,它实现了可变长的数组(不推荐使用)。而LinkedList 则有些不同,它是List的链表实现。  LinkedList 可以成为堆栈,队列或者双向链表。  SetExample.java import  java.util.HashSet; import  java.util.Set; public   class  SetExample {    public static void main( String args[] )    {        Set set = new HashSet();        set.add("one");        set.add("second");        set.add("3rd");        set.add(new Integer(4));        set.add(new Float(5.0F));        set.add("second");  //duplicate, not added        set.add(new Integer(4));   //duplicate, not added        System.out.println(set);    }} 输出:one, 4, 5.0, 3rd, second ListExample.java import  java.util.ArrayList; import  java.util.List; /** * @author 罗锋 , 创建时间Feb 5, 2007 */ public   class  ListExample {    /**     * @param args     */    public static void main(String[] args)    {        List list = new ArrayList();        list.add("one");        list.add("second");        list.add("3rd");        list.add(new Integer(4));        list.add(new Float(5.0F));        list.add("second");  //duplicate, is added        list.add(new Integer(4));   //duplicate, is added        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 import  java.util.Enumeration; import  java.util.Properties; /** * @author 罗锋 , 创建时间Feb 6, 2007 */ public   class  PropertiesExample {    /**     * @param args     */    public static void main(String[] args)    {        Properties props = System.getProperties();        Enumeration prop_names = props.propertyNames();        while( prop_names.hasMoreElements())        {            String prop_name = (String)prop_names.nextElement();            String property = props.getProperty(prop_name);            System.out.println("property " + prop_name + " is" + property + " ");        }    }}

    最新回复(0)