- 论坛徽章:
- 0
|
Map与HashMap的使用
一、HashMapDemo类用于构建需要放进Map中的对象- package hashmap;
- public class HashMapDemo {
- private String name;
- private String school;
- public HashMapDemo(String name,String school){
- this.name=name;
- this.school = school;
- }
- public String toString(){
- return school+"毕业的"+name;
- }
- }
复制代码 二、用于测式HashMap类中的对象- package hashmap;
- import java.util.HashMap;
- import java.util.Map;
- public class HashMapTest {
- public static void main(String[] args) {
- HashMapDemo stu1=new HashMapDemo("李明","北京中心");
- HashMapDemo stu2 = new HashMapDemo("刘丽","天津中心");
-
- Map students=new HashMap();
- //把英文名称与学员对象按照"键-值对"的方式存储在HashMap中
- students.put("Jack", stu1);
- students.put("rose", stu2);
- //分别打印键集、值集、以及键-值对集合
- System.out.println("键集:"+students.keySet());
- System.out.println("值集:"+students.values());
- System.out.println("键-值对集合:"+students);
-
- String key="Jack";
- //判断是否存在某个键,如果是同,则根据键获取相应的值
- if(students.containsKey(key)){
- System.out.println(students.get(key));
- }
-
- //根据键删除某个值
- students.remove(key);
- System.out.println(students);
-
- }
- }
复制代码 总结:
1、存储数据到HashMap中用Map 对象.put("键",值)。
2、获取键集使用Map 对象.keySet()方法。
3、判断是否存在某个键用 Map对象.containsKey(键)方法。
4、获取某个键所对应的值使用Map 对象.get(键)方法。
5、根据键删除Map对象中某个对象使用Map 对象.remove(键)方法。 |
|