Java中通过HashMap来存取数据的小知识点

来源:互联网 发布:windows10壁纸软件 编辑:程序博客网 时间:2024/05/17 08:11

HashMap有两种方式来迭代获取集合中存储的键值对

第一种:keySet()方法,该方法会返回一个Set集合,然后通过迭代这个集合来获取HashMap中存储的值

第二种:entrySet()方法,该方法会返回一个支持泛型的Set对象:格式为Set<Map.Entry> ,然后通过迭代这个set集合来获取HashMap中存储的值

要注意的是:HashMap中要求键是唯一的,如果键重复,那么后put()的对象会覆盖之前的对象,键唯一,而值不唯一

import java.util.*;class StudentMap {public static void main(String[] args) {HashMap<Integer,Student> hm =new HashMap<Integer,Student>();//创建集合对象hm.put(1,new Student("li1",20));hm.put(1,new Student("li1",22));//键都是1,那么则会覆盖上面那个学生对象hm.put(3,new Student("li2",20));hm.put(4,new Student("li1",20));hm.put(5,new Student("li2",20));//向集合中添加元素Set<Integer> set=hm.keySet();//获得包含键视图的set集合Iterator<Integer> it = set.iterator();//获得set集合的迭代器while(it.hasNext()){Integer i = it.next();sop(i+"="+hm.get(i));//迭代输出每一个键}//Set<Map.Entry<Integer,Student>> entry = hm.entrySet();//获取包含Map.Entry键值对的Set集合//Iterator<Map.Entry<Integer,Student>> it = entry.iterator();//获取迭代器//while(it.hasNext())//{//Map.Entry<Integer,Student> me = it.next();//将Map.Entry对象赋值给me//sop(me.getKey()+"="+me.getValue());//调用Map.Entry对象的方法来输出内容//}}public static void sop(Object obj){System.out.println(obj);}}

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

这是简单的student类

class Student {private String name = null;private int age = 0;public Student(String name,int age){this.name=name;this.age=age;}public String getName(){return this.name;}public int getAge(){return this.age;}public String toString()//覆盖toString方法{return "["+this.name+","+this.age+"]";}public int hashCode()//覆盖hashCode方法{return this.name.hashCode()+this.age*27;}}

import java.util.*;class StudentMap {public static void main(String[] args) {HashMap<Integer,Student> hm =new HashMap<Integer,Student>();//创建集合对象hm.put(1,new Student("li1",20));hm.put(1,new Student("li1",22));//键都是1,那么则会覆盖上面那个学生对象hm.put(3,new Student("li2",20));hm.put(4,new Student("li1",20));hm.put(5,new Student("li2",20));//向集合中添加元素Set<Integer> set=hm.keySet();//获得包含键视图的set集合Iterator<Integer> it = set.iterator();//获得set集合的迭代器while(it.hasNext()){Integer i = it.next();sop(i+"="+hm.get(i));//迭代输出每一个键}//Set<Map.Entry<Integer,Student>> entry = hm.entrySet();//获取包含Map.Entry键值对的Set集合//Iterator<Map.Entry<Integer,Student>> it = entry.iterator();//获取迭代器//while(it.hasNext())//{//Map.Entry<Integer,Student> me = it.next();//将Map.Entry对象赋值给me//sop(me.getKey()+"="+me.getValue());//调用Map.Entry对象的方法来输出内容//}}public static void sop(Object obj){System.out.println(obj);}}

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

这是简单的student类

class Student {private String name = null;private int age = 0;public Student(String name,int age){this.name=name;this.age=age;}public String getName(){return this.name;}public int getAge(){return this.age;}public String toString()//覆盖toString方法{return "["+this.name+","+this.age+"]";}public int hashCode()//覆盖hashCode方法{return this.name.hashCode()+this.age*27;}}

0 0
原创粉丝点击