本篇介紹java.util.Map接口下的兩個方法HashMap與Hashtable
HashMap與Hashtable的差別在于狀态,前者:非同步;後者:同步(線程)
注:HashMap筆者認為是無序映射集合,Hashtable是按添加順序排列(未證明)
1.HashMap>>
- package cn.test.map;
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.Set;
- import java.util.Map.Entry;
- public class TestHashMap {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- HashMap<Integer, Person> hm = new HashMap<Integer, Person>();
- hm.put(10, new Person("小沈陽", 20, "中國"));
- hm.put(2, new Person("沈陽", 20, "日本"));
- hm.put(40, new Person("小沈", 20, "美國"));
- hm.put(25, new Person("小陽", 20, "英國"));
- //去鍵存入Set中
- Set<Integer> s = hm.keySet();
- for (int i : s) {
- System.out.println(i);
- }
- //取值存入Collection
- Collection<Person> c = hm.values();
- for (Person p : c) {
- System.out.println(p.getName());
- }
- //轉換成set集合(鍵值對)
- Set<Entry<Integer, Person>> st = hm.entrySet();
- for(Entry<Integer,Person> e:st)
- {
- Person p=e.getValue();
- System.out.println(e.getKey()+"\t"+p.getName()+"\t"+p.getAge()+"\t"+p.getAddress());
- }
- }
- }
- package cn.test.map;
- import java.util.Collection;
- import java.util.Hashtable;
- import java.util.Set;
- import java.util.Map.Entry;
- public class TestHashTable {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Hashtable<Integer, Person> ht = new Hashtable<Integer, Person>();
- ht.put(32, new Person("小沈陽", 20, "北京"));
- ht.put(102, new Person("趙本山", 23, "遼甯"));
- ht.put(22, new Person("老胡", 76, "未知"));
- Set<Integer> s = ht.keySet();
- for (Integer i : s) {
- System.out.println(i);
- }
- Collection<Person> c = ht.values();
- for (Person p : c) {
- System.out.println(p.getName() + "\t" + p.getAge() + "\t"
- + p.getAddress());
- }
- Set<Entry<Integer, Person>> se = ht.entrySet();
- for (Entry<Integer, Person> e : se) {
- Person p = e.getValue();
- System.out.println(e.getKey() + "\t" + p.getName() + "\t"
- + p.getAge() + "\t" + p.getAddress());
- }
- }
- }
- package cn.test.map;
- public class Person {
- private String name;
- private int age;
- private String address;
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return this.name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- public Person(String name, int age, String adress) {
- this.name = name;
- this.age = age;
- this.address = adress;
- }
- }