1. 程式人生 > >java中的幾種泛型類——HashSet、HashMap、TreeSet、TreeMap,遍歷map,排序,HashTable比較

java中的幾種泛型類——HashSet、HashMap、TreeSet、TreeMap,遍歷map,排序,HashTable比較

package test;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class Sort {

	public static void main(String[] args) {
		System.out.println("開始:");
		Person person1 = new Person("馬先生", 220181);
		Person person2 = new Person("李先生", 220193);
		Person person3 = new Person("王小姐", 220186);
		Map<Number, Person> map = new HashMap<Number, Person>();
		map.put(person1.getIdCard(), person1);
		map.put(person2.getIdCard(), person2);
		map.put(person3.getIdCard(), person3);
		System.out.println("由HashMap類實現的Map集合,無序:");
		for (Iterator<Number> it = map.keySet().iterator(); it.hasNext();) {// 遍例集合
			Person person = map.get(it.next());
			System.out.println(person.getIdCard() + " " + person.getName());
		}
		System.out.println("由TreeMap類實現的Map集合,鍵物件升序:");
		TreeMap<Number, Person> treeMap = new TreeMap<Number, Person>();
		treeMap.putAll(map);
		for (Iterator<Number> it = treeMap.keySet().iterator(); it.hasNext();) {// 遍例集合
			Person person = treeMap.get(it.next());
			System.out.println(person.getIdCard() + " " + person.getName());
		}
		System.out.println("由TreeMap類實現的Map集合,鍵物件降序:");
		TreeMap<Number, Person> treeMap2 = new TreeMap<Number, Person>(
				Collections.reverseOrder());// 初始化為反轉排序
		treeMap2.putAll(map);
		for (Iterator it = treeMap2.keySet().iterator(); it.hasNext();) {// 遍例集合
			Person person = (Person) treeMap2.get(it.next());
			System.out.println(person.getIdCard() + " " + person.getName());
		}
		System.out.println("結束!");
	}
}

class Person {
	private String name;
	private long idCard;

	public Person(String name, long idCard) {
		this.name = name;
		this.idCard = idCard;
	}

	public long getIdCard() {
		return idCard;
	}

	public void setIdCard(long idCard) {
		this.idCard = idCard;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

     輸出結果為:
開始:
由HashMap類實現的Map集合,無序:
220186 王小姐
220181 馬先生
220193 李先生
由TreeMap類實現的Map集合,鍵物件升序:
220181 馬先生
220186 王小姐
220193 李先生
由TreeMap類實現的Map集合,鍵物件降序:
220193 李先生
220186 王小姐
220181 馬先生
結束!