美文网首页
Map常见子类对象、HashMap存储自定义对象

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

作者: vv_64ce | 来源:发表于2018-12-12 21:14 被阅读0次

    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<Student,String> map = new HashMap<Student,String>();
            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<Student> set = map.keySet();
            Iterator<Student> 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<Student,String> ts = new TreeMap<Student,String>(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<Map.Entry<Student, String>> set = ts.entrySet();
            Iterator<Map.Entry<Student, String>> it = set.iterator();
            while(it.hasNext()){
                Map.Entry<Student, String> map = it.next();
                Student key = map.getKey();
                String value = map.getValue();
                System.out.println( key.getAge()+ ":" + key.getName() + ":" + value);
            }
    
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:Map常见子类对象、HashMap存储自定义对象

          本文链接:https://www.haomeiwen.com/subject/waaphqtx.html