Java 集合 Collection ArrayList HashMap Hashtable Queue

Java 集合 Collection ArrayList HashMap Hashtable Queue

package com.ssm.cts.test;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;

public class CollectionTest {

  public static void getList() {
    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    
    for (String str : list) {
      System.out.println(str);
    }

    for (int i = 0; i < list.size(); i++) {
      System.out.println(list.get(i).toString());
    }
  }
  
  public static void getMap() {
    Map<String, String> map = new HashMap<String, String>();
    map.put("1", "a");
    map.put("2", "b");
    map.put("3", "c");

    System.out.println("通过Map.keySet遍历key和value:");
    for (String key : map.keySet()) {
      System.out.println("key= " + key + " and value= " + map.get(key));
    }
  }
  
  public static void getHashTable() {
    Hashtable ht = new Hashtable();
    ht.put("1", "a");
    ht.put("2", "b");
    ht.put("3", "c");

    Enumeration em = ht.elements();
    while (em.hasMoreElements()) {
      String obj = (String) em.nextElement();
      System.out.println(obj);
    }

    Iterator<String> iterator = ht.keySet().iterator();
    while (iterator.hasNext()) {
      String key = (String) iterator.next();
      String value = (String) ht.get(key);
      System.out.println("keySet:" + key + " " + value);
    }

  }
  
  public static void getQueue() {
    Queue<String> queue = new LinkedList<String>();
    // 添加元素
    queue.offer("a");
    queue.offer("b");
    queue.offer("c");
    queue.offer("d");
    queue.offer("e");
    for (String q : queue) {
      System.out.println(q);
    }
    System.out.println("===");
    System.out.println("poll=" + queue.poll()); // 返回第一个元素,并在队列中删除
    for (String q : queue) {
      System.out.println(q);
    }
  }
  
  public static void main(String[] args) {
    getList();
    getMap();
    getHashTable();
    getQueue();
  }
}

 

发表回复

您的电子邮箱地址不会被公开。