首页 > 编程语言 > 详细

java 中容易误解的地方

时间:2015-05-30 02:08:26      阅读:266      评论:0      收藏:0      [点我收藏+]

1,equals

@Test
    public void test_equal(){
        String a="1";
        int b=1;
        boolean result=a.equals(b);
        System.out.println(result);
    }

我以为会报错的,因为类型不同啊,一个是字符串,一个是整型. 结果没有报错.

原因:equals 比较时自动把基本类型转化为包装类型了?
运行结果是:?
false?
应该改为:

@Test
    public void test_equal(){
        String a="1";
        int b=1;
        boolean result=a.equals(String.valueOf(b));
        System.out.println(result);
    }

?

2,包装类型

@Test
    public void test_equal2(){
        Long a=229L;
        Long b=229L;
        System.out.println((a==b));
    }

?运行结果:false

?

@Test
    public void test_equal2(){
        Long a=29L;
        Long b=29L;
        System.out.println((a==b));
    }

?运行结果为:true?

?

应该改为:

@Test
    public void test_equal2(){
        Long a=229L;
        Long b=229L;
        System.out.println((a.intValue()==b.intValue()));
    }

?

?

3,把json字符串反序列化为对象

当json字符串是空时竟然不报错,示例如下:

ObjectMapper mapper = new ObjectMapper();
		Student2 student;
		try {
			student = mapper.readValue("{}", Student2.class);
			System.out.println(student.getClassroom());
			System.out.println(student.getSchoolNumber());
		} catch (Exception e) {
			e.printStackTrace();
		}

?运行结果:
bubuko.com,布布扣
?

?

但是,如果json字符串中包含的属性,对象中没有则报错

ObjectMapper mapper = new ObjectMapper();
		Student2 student;
		try {
			student = mapper.readValue("{\"username2323\":\"whuang\"}", Student2.class);
			System.out.println(student.getClassroom());
			System.out.println(student.getSchoolNumber());
		} catch (Exception e) {
			e.printStackTrace();
		}

?Student2类中没有属性username2323

报错信息:

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "username2323" (Class tv_mobile.Student2), not marked as ignorable
 at [Source: java.io.StringReader@7bb613c0; line: 1, column: 18] (through reference chain: tv_mobile.Student2["username2323"])
	at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)

?

参考:http://blog.csdn.net/hw1287789687

http://blog.csdn.net/hw1287789687/article/details/45916001

?

作者:黄威

?

java 中容易误解的地方

原文:http://hw1287789687.iteye.com/blog/2215528

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!