Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2566323
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-09-19 15:34:00

java.util..get( key)

  • get get( key)
    Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

    More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

    If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The operation may be used to distinguish these two cases.

    Parameters: key - the key whose associated value is to be returned Returns: the value to which the specified key is mapped, or null if this map contains no mapping for the key Throws: - if the key is of an inappropriate type for this map () - if the specified key is null and this map does not permit null keys ()


表结构如下:
create table user(
id int not null primary key,
roleid int not null ,
deptid int not null,
tlid int null,
email varchar(50) not null,
password varchar(50) not null
);

当使用map的get方法时抛出null异常,
  1. if (map.get("tlid")!=null) {
  2.                 user.setTlid((Integer)map.get("tlid"));
  3.             }


将代码改为以下:显示正常。
  1. if(map.containsKey("tlid")){
  2.             //if (!map.get("tlid").equals(null)) {
  3.             if (map.get("tlid")!=null) {
  4.                 user.setTlid((Integer)map.get("tlid"));
  5.             }
  6.             
  7.         }

以下两句代码的区别:
  1. if (!map.get("tlid").equals(null)) {

map.get("tlid")为null时,抛出空指针异常。正确写法:
  1. if (map.get("tlid")!=null) {


  完整代码:       

  1. private User populate(Map<String, Object> map) {
  2.         User user = new User();
  3.         user.setId((Integer) map.get("id"));
  4.         user.setRoleid((Integer) map.get("roleid"));
  5.         user.setDeptid((Integer)map.get("deptid"));
  6.         /*
  7.          * foreign key..,no map.. omit these attr
  8.          */
  9.         if(map.containsKey("tlid")){
  10.             //if (!map.get("tlid").equals(null)) {
  11.             if (map.get("tlid")!=null) {
  12.                 user.setTlid((Integer)map.get("tlid"));
  13.             }
  14.             
  15.         }
  16.         user.setEmail((String) map.get("email"));
  17.         user.setPassword((String) map.get("password"));
  18.         
  19.         return user;
  20.     }
阅读(7047) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~