Java常用数据结构使用举例

Enumeration:

import java.util.Vector;

import java.util.Enumeration;

public static void enumerationDemo() {

    Vector<String> fruits = new Vector<String>();

    fruits.add("Apple");

    fruits.add("Banana");

    fruits.add("Pear");

    fruits.add("Pinapple");

    Enumeration<String> fruitEnum = fruits.elements();

扫描二维码关注公众号,回复: 2433649 查看本文章

    while (fruitEnum.hasMoreElements()) {

        System.out.println(fruitEnum.nextElement());

    }

}

// 输出

// Apple

// Banana

// Pear

// Pinapple

BitSet:

import java.util.BitSet;

public static void bitSetDemo() {

    BitSet bs1 = new BitSet(16);

    BitSet bs2 = new BitSet(16);

    for (int i = 0; i < 16; i+=2) {

        bs1.set(i);             // set to true

        bs2.set(i+1, true);     // also set to true

    }

    System.out.println(bs1);    //bs1:1010 1010 1010 1010

    System.out.println(bs2);    //bs2:0101 0101 0101 0101

    

    BitSet bs3 = new BitSet(16);

    //bs3:1111 1111 1111 1111

    bs3.set(0, 8);

    bs3.set(8, 16, true);

    System.out.println(bs3);

    

    // 'not' bs1 = !(1010 1010 1010 1010) = 0101 0101 0101 0101, 

    // bs3 'and' ('not' bs1) = 0101 0101 0101 0101 & 1111 1111 1111 1111

    //                       = 0101 0101 0101 0101

    bs3.andNot(bs1);

    System.out.println(bs3);

    

    // cardinality returns how many 'true' were set in the bitset, here we got 8

    System.out.println(bs3.cardinality());

    

    bs1.and(bs2);               //bs1:0000 0000 0000 0000

    System.out.println(bs1);

    

    bs1.set(8, 16, true);       //bs1:0000 0000 1111 1111

    System.out.println(bs1);

    

    bs1.clear(13);              //bs1:0000 0000 1111 1011

    System.out.println(bs1);

    

    bs3 = (BitSet)bs1.clone();  //bs3:0000 0000 1111 1011

    bs1.clear(8, 12);           //bs1:0000 0000 0000 1011

    System.out.println(bs1);

    System.out.println(bs3);

    bs1.clear();                //bs1:0000 0000 0000 0000

    

    System.out.println(bs1.equals(bs3));

    bs1.flip(1, 15);            //bs1:0111 1111 1111 1110

    System.out.println(bs1);

    bs1.flip(10);               //bs1:0111 1111 1101 1110

    

    System.out.println(bs1.get(10));

    

    bs1.xor(bs3);               //bs1:0111 1111 0010 0101

    System.out.println(bs1);

    

    BitSet bs4 = bs1.get(4, 12);    //bs4:1111 1101

    System.out.println(bs4);

    System.out.println(bs4.hashCode()); // get hash code for this set

    

    BitSet bs5 = new BitSet(8);

    bs5.set(0, 4);          //bs5:1111 0000

    BitSet bs6 = new BitSet(8);

    bs6.set(4, 8);          //bs6:0000 1111

    // bs5 and bs6 don't have a same bit that is set to 'true', 

    // intersects will return false

    System.out.println(bs5.intersects(bs6));

    bs6.set(2);         //bs6:0010 1111

    // bs5 and bs6 intersects at bit '2'

    System.out.println(bs5.intersects(bs6));

    

    // nextClearBit returns the index of the first bit

    // that is set to false starting from the specified index

    System.out.println(bs5.nextClearBit(0));

    // nextClearBit returns the index of the first bit

    // that is set to true starting from the specified index

    System.out.println(bs6.nextSetBit(0));

    

    bs5.or(bs6);    //bs5:1111 1111

    System.out.println(bs5);

    

    BitSet bs7 = new BitSet(16);

    //size returns the number of bits os space actually in use by this set

    System.out.println(bs7.size());

    //length returns the "logic size": the index of the highest set bit + 1

    bs7.set(9);

    System.out.println(bs7.length());

}

FixedArray &ArrayList:

import java.util.ArrayList;

import java.util.Set;

import java.util.HashSet;

public static void arrayDemo() {

    // fix-sized array =============================================

    int[] arr1 = new int[10];

    String[] arr2 = {"a", "b", "c", "d", "e"};

    String[] arr3 = new String[]{"a", "b", "c"};

    

    System.out.println(Arrays.toString(arr1));

    //output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    System.out.println(Arrays.toString(arr2));

    //output: [a, b, c, d, e]

    

    ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr2));

    System.out.println(arrList);

    //output: [a, b, c, d, e]

    

    String[] arr4 = new String[arrList.size()];

    arrList.toArray(arr4);

    System.out.println(Arrays.toString(arr4));

    //output: [a, b, c, d, e]

    

    Set<String> set = new HashSet<String>(Arrays.asList(arr4));

    System.out.println(set);

    //output: [a, b, c, d, e]

    

    //dynamic array list =============================================

    ArrayList<Integer> list1 = new ArrayList<Integer>();

    ArrayList<Integer> list2 = new ArrayList<Integer>(10);

    for (int i = 0; i < 10; i++) {

        list2.add(i);

    }

    ArrayList<Integer> list3 = new ArrayList<Integer>(list2);

    System.out.println(list3);

    //output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    

    System.out.println(list1.isEmpty());

    //output: true

    

    list1.addAll(list3);

    System.out.println(list1);

    //output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    list1.addAll(5, list3);

    System.out.println(list1);

    //output: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9]

    

    System.out.println(list1.containsAll(list2));

    //output: true

    list2.add(10);

    System.out.println(list1.containsAll(list2));

    //output: false

    

    System.out.println(list1.indexOf(4));

    //output: 4

    System.out.println(list1.lastIndexOf(4));

    //output: 9

    

    System.out.println(list1.size());

    //output: 20

    

    System.out.println(list1.subList(4, 10));

    //output: [4, 0, 1, 2, 3, 4]

    

    ArrayList<Integer> list4 = (ArrayList<Integer>)list1.clone();

    list1.clear();

}

Vector:

import java.util.Vector;

import java.util.List;

public static void vectorDemo() {

    //constructors

    Vector<String> vec1 = new Vector<String>();

    Vector<String> vec2 = new Vector<String>(10);

    Vector<String> vec3 = new Vector<String>(10, 3);

    String[] arr1 = {"a", "b", "c", "d", "e"};

    Vector<String> vec4 = new Vector<String>(Arrays.asList(arr1));

    

    //add methods

    for (int i = 0; i < 10; i++) {

        vec1.add(String.format("%d", i));

    }

    //vec1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    vec2.addAll(vec4);

    //vec2: [a, b, c, d, e]

    vec2.addAll(3, vec1);

    //vec2: [a, b, c, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, d, e]

    vec2.add(8, "test");

    //vec2: [a, b, c, 0, 1, 2, 3, 4, test, 5, 6, 7, 8, 9, d, e]

    vec2.addElement("abc");

    //vec2: [a, b, c, 0, 1, 2, 3, 4, test, 5, 6, 7, 8, 9, d, e, abc]

    vec2.insertElementAt("def", 3);

    //vec2: [a, b, c, def, 0, 1, 2, 3, 4, test, 5, 6, 7, 8, 9, d, e, abc]

    

    //get methods

    Enumeration<String> iter = vec2.elements();

    while(iter.hasMoreElements()) {

        System.out.println(iter.nextElement());

    }

    String strAtPos3 = vec2.get(3);     //position starts at index 0

    String strAtPos3_1 = vec2.elementAt(3); //position starts at index 0

    String firstStr = vec2.firstElement();  //a

    String lastStr = vec2.lastElement();    //abc

    

    //Vector basic methods

    System.out.println(vec2.capacity());    //20, capacity is pre-allocated size

    System.out.println(vec2.size());    //18, size is the number of elements

    System.out.println(vec2.isEmpty()); //false

    //if newSize is greater than current size, null elements will be appended,

    //if newSize is less than current size, all elements after index "newSize"

    //will be discarded

    vec2.setSize(15);

    //vec2: [a, b, c, def, 0, 1, 2, 3, 4, test, 5, 6, 7, 8, 9]

    vec2.trimToSize();  //trim empty positions, capacity will be equal to size

    //enlarge capacity, at lease the capacity should hold the size

    vec2.ensureCapacity(10);    //capacity should be 15 now

    Vector<String> vecNew = (Vector<String>)vec2.clone();

    System.out.println(vec2.hashCode());

    System.out.println(vecNew.equals(vec2));

    

    //index and contain methods

    System.out.println(vec2.indexOf("test")); //9 (index starts at 0)

    System.out.println(vec2.indexOf("1", 8)); //-1 (Searching starts at index 8)

    System.out.println(vec2.lastIndexOf("test")); //9

    System.out.println(vec2.lastIndexOf("test", 6)); //-1 (Searching from index 6 to 0)

    System.out.println(vec2.contains("test"));

    System.out.println(vec2.containsAll(vec1)); //vec1: [0,1,2,3,4,5,6,7,8,9]

    

    //set methods

    vec2.set(0, "Start");

    //vec2: [Start, b, c, def, 0, 1, 2, 3, 4, test, 5, 6, 7, 8, 9]

    vec2.setElementAt("SecElem", 1);

    //vec2: [Start, SecElem, c, def, 0, 1, 2, 3, 4, test, 5, 6, 7, 8, 9]

    System.out.println(vec2);

    

    //remove methods

    vecNew.remove(10); 

    //vecNew: [a, b, c, def, 0, 1, 2, 3, 4, test, 6, 7, 8, 9]

    //remove the first match element

    vecNew.remove("2");

    //vecNew: [a, b, c, def, 0, 1, 3, 4, test, 6, 7, 8, 9]

    vecNew.removeAll(vec4);

    //vecNew: [def, 0, 1, 3, 4, test, 6, 7, 8, 9]

    vecNew.removeElementAt(2);

    //vecNew: [def, 0, 3, 4, test, 6, 7, 8, 9]

    vecNew.removeElement("4");

    //vecNew: [def, 0, 3, test, 6, 7, 8, 9]

    //remove all elements that are not contained in the param collection

    vecNew.retainAll(vec1);

    //vecNew: [0, 3, 6, 7, 8, 9]

    vecNew.removeAllElements(); //size will be 0, capacity will remain

    vecNew.clear();         //similar to removeAllElements

    System.out.println(vecNew);

    

    //convert methods

    String[] sArr = new String[vec2.size()];

    vec2.copyInto(sArr);

    //sArr: [Start, SecElem, c, def, 0, 1, 2, 3, 4, test, 5, 6, 7, 8, 9]

    List l = vec2.subList(6, 10);

    //l: [2, 3, 4, test]

    Object[] ol1 = vec2.toArray();

    for (int i = 0; i < ol1.length; i++) {

        System.out.println(ol1[i]);

    }

    String[] targetArr = new String[vec2.size()];

    vec2.<String>toArray(targetArr);

    //targetArr: [Start, SecElem, c, def, 0, 1, 2, 3, 4, test, 5, 6, 7, 8, 9]

    System.out.println(vec2.toString());

}

Stack:

Stack继承自Vector,所以Stack继承了Vector中定义的全部方法,除了Vector中的方法,Stack还定义了一些自己特有的方法

import java.util.Stack;

public static void stackDemo() {

    //Stack is derived from Vector

    Stack<Integer> s1 = new Stack<Integer>();

    for (int i = 0; i < 10; i+=2) {

        s1.push(i);

    }

    System.out.println(s1); //[0, 2, 4, 6, 8]

    System.out.println(s1.peek());  //8

    Integer top = s1.pop();

    System.out.println(top);  //8

    System.out.println(s1.peek());  //6

    System.out.println(s1.search(2));  //3

    System.out.println(s1.search(3));  //-1

}

Dictionary:

Dictionary是抽象类,不能实例化,Hashtable就是一个Dictionary的实现类,不过Dictionary已经过时,目前通常使用Map接口,Hashtable也实现了Map接口的方法

Hashtable:

import java.util.Hashtable;

public static void hashtableDemo() {

    Hashtable<String, Integer> ht1 = new Hashtable<String, Integer>();

    for (int i = 0; i < 10; i++) {

        ht1.put(String.format("Test%d", i), i);

    }

    Hashtable<String, Integer> ht2 = (Hashtable<String, Integer>)ht1.clone();

    Hashtable<String, Integer> ht3 = new Hashtable<String, Integer>(10, 0.8f);

    

    System.out.println(ht3.isEmpty());  //true

    System.out.println(ht2.size());     //10

    

    Enumeration<Integer> values = ht2.elements();

    while (values.hasMoreElements()) {

        System.out.println(values.nextElement());

    }

    

    if (ht2.contains(5)) {    // or use containsValue(5)

        Enumeration<String> keys = ht2.keys();

        while (keys.hasMoreElements()) {

        String key = keys.nextElement();

        Integer value = ht2.get(key);

        if (value == 5) {

            System.out.println(key);

        }

        }

    }

    

    if (ht2.containsKey("Test2")) {

        System.out.println(ht2.get("Test2"));

    }

    

    ht1.clear();

    System.out.println(ht2);

    ht2.remove("Test5");

    System.out.println(ht2);

}

Map:

import java.util.Map;

import java.util.HashMap;

import java.util.Set;

import java.util.Collection;

public static void hashmapDemo() {

    Map<Integer, String> m1 = new HashMap<Integer, String>();

    for (int i = 0; i < 10; i++) {

        m1.put(i, String.format("Test%d", i));

    }

    System.out.println(m1);

    

    Set<Map.Entry<Integer, String>> set = m1.entrySet();

    for (Map.Entry<Integer, String> entry : set) {

        System.out.println(entry.getKey() + ":" + entry.getValue());

    }

    

    System.out.println(m1.containsKey(4));

    System.out.println(m1.containsValue("Test5"));

    

    Set<Integer> keys = m1.keySet();

    Collection<String> values = m1.values();

    m1.remove(6);

    

    System.out.println(keys);

    System.out.println(values);

}

Set:

Set不包含重复元素

import java.util.ArrayList;

import java.util.Set;

public static void setDemo() {

    int[] nums = new int[] {1, 4, 8, 3, 22, 34, 4, 6, 0, 33, 5, 6, 3, 9};

    List list = new ArrayList();

    for (int i:nums) {

        list.add(i);

    }

    System.out.println(list);

    //[1, 4, 8, 3, 22, 34, 4, 6, 0, 33, 5, 6, 3, 9]

    Set<Integer> set = new HashSet<Integer>();

    

    //remove duplicate elements

    set.addAll(list);

    System.out.println(set);

    //[0, 1, 33, 34, 3, 4, 5, 22, 6, 8, 9]

    set.add(4);   //4 is a duplicate element, so this will not take effect

    System.out.println(set);

    //[0, 1, 33, 34, 3, 4, 5, 22, 6, 8, 9]

    

    System.out.println(set.size());    //11

}

Properties:

Properties 继承于Hashtable.表示一个持久的属性集.属性列表中每个键及其对应值都是一个字符串

import java.util.Properties;

public static void propertiesDemo() {

    Properties props = new Properties();

    props.put("Key1", "Value1");

    props.setProperty("Key2", "Value2");

    props.list(System.out);

    //-- listing properties --

    //Key2=Value2

    //Key1=Value1

    System.out.println(props.getProperty("Key1"));  //Value1

}

猜你喜欢

转载自blog.csdn.net/chengxuyuan_110/article/details/81115818