本篇介绍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;
- }
- }