天天看点

java 中容易误解的地方

1,equals

java 中容易误解的地方

@test  

    public void test_equal(){  

        string a="1";  

        int b=1;  

        boolean result=a.equals(b);  

        system.out.println(result);  

    }  

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

原因:equals 比较时自动把基本类型转化为包装类型了 

运行结果是: 

false 

应该改为:

java 中容易误解的地方

        boolean result=a.equals(string.valueof(b));  

2,包装类型

java 中容易误解的地方

    public void test_equal2(){  

        long a=229l;  

        long b=229l;  

        system.out.println((a==b));  

 运行结果:false

java 中容易误解的地方

        long a=29l;  

        long b=29l;  

 运行结果为:true 

java 中容易误解的地方

        system.out.println((a.intvalue()==b.intvalue()));  

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

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

java 中容易误解的地方

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();  

        }  

 运行结果:

java 中容易误解的地方

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

java 中容易误解的地方

            student = mapper.readvalue("{\"username2323\":\"whuang\"}", student2.class);  

 student2类中没有属性username2323

报错信息:

java 中容易误解的地方

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/article/details/45916001

作者:黄威