Map常见子类对象、HashMap存储自定义对象

Map常用的子类:

  1. |---Hashtable:内部结构是哈希表,是同步的,不允许null作为键,null作为值
    |--Properties:用来存储键值对型的配置文件的信息。可以和IO技术相结合。
  2. |---HashMap:内部结构是哈希表,不是同步的,允许null作为键,null作为值。
  3. |---TreeMap:内部结构是二叉树,不是同步的,可以对Map集合中的键进行排序
    HashMap存储自定义对象:
    将学生对象和学生归属地通过键与值存储到map集合中。

HashMap

package com.vv.map.demo;

import java.io.ObjectInputStream.GetField;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.vv.bean.Student;

public class HashMapDemo {

    public static void main(String[] args) {

        HashMap map = new HashMap();
        map.put(new Student("zhangsan",12),"上海");
        map.put(new Student("lisi",22),"北京");
        map.put(new Student("zhangsan",12),"天津");
        map.put(new Student("zhaoliu",12),"成都");

        Set set = map.keySet();
        Iterator it = set.iterator();
        while(it.hasNext()){
            Student key = it.next();
            String value = map.get(key);
            System.out.println( key.getAge()+ ":" + key.getName() + ":" + value);
        }
    }

}

TreeMap

package com.vv.map.demo;

import java.nio.MappedByteBuffer;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.vv.bean.Student;
import com.vv.comparator.ComparatorByName;

public class TreeSetMap {

    public static void main(String[] args) {
        TreeMap ts = new TreeMap(new ComparatorByName());
        ts.put(new Student("zhangsan",12),"上海");
        ts.put(new Student("lisi",22),"北京");
        ts.put(new Student("zhangsan",12),"天津");
        ts.put(new Student("zhaoliu",12),"成都");

        Set> set = ts.entrySet();
        Iterator> it = set.iterator();
        while(it.hasNext()){
            Map.Entry map = it.next();
            Student key = map.getKey();
            String value = map.getValue();
            System.out.println( key.getAge()+ ":" + key.getName() + ":" + value);
        }

    }

}

你可能感兴趣的:(Map常见子类对象、HashMap存储自定义对象)