天天看點

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

作者:黃威