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(键)方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值