java 中容易误解的地方

1,equals

Java代码  java 中容易误解的地方
  1. @Test  
  2.     public void test_equal(){  
  3.         String a="1";  
  4.         int b=1;  
  5.         boolean result=a.equals(b);  
  6.         System.out.println(result);  
  7.     }  

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

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

Java代码  java 中容易误解的地方
  1. @Test  
  2.     public void test_equal(){  
  3.         String a="1";  
  4.         int b=1;  
  5.         boolean result=a.equals(String.valueOf(b));  
  6.         System.out.println(result);  
  7.     }  

 

2,包装类型

Java代码  java 中容易误解的地方
  1. @Test  
  2.     public void test_equal2(){  
  3.         Long a=229L;  
  4.         Long b=229L;  
  5.         System.out.println((a==b));  
  6.     }  

 运行结果:false

 

Java代码  java 中容易误解的地方
  1. @Test  
  2.     public void test_equal2(){  
  3.         Long a=29L;  
  4.         Long b=29L;  
  5.         System.out.println((a==b));  
  6.     }  

 运行结果为:true 

 

应该改为:

Java代码  java 中容易误解的地方
  1. @Test  
  2.     public void test_equal2(){  
  3.         Long a=229L;  
  4.         Long b=229L;  
  5.         System.out.println((a.intValue()==b.intValue()));  
  6.     }  

 

 

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

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

Java代码  java 中容易误解的地方
  1. ObjectMapper mapper = new ObjectMapper();  
  2.         Student2 student;  
  3.         try {  
  4.             student = mapper.readValue("{}", Student2.class);  
  5.             System.out.println(student.getClassroom());  
  6.             System.out.println(student.getSchoolNumber());  
  7.         } catch (Exception e) {  
  8.             e.printStackTrace();  
  9.         }  

 运行结果:
java 中容易误解的地方
 

 

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

Java代码  java 中容易误解的地方
  1. ObjectMapper mapper = new ObjectMapper();  
  2.         Student2 student;  
  3.         try {  
  4.             student = mapper.readValue("{\"username2323\":\"whuang\"}", Student2.class);  
  5.             System.out.println(student.getClassroom());  
  6.             System.out.println(student.getSchoolNumber());  
  7.         } catch (Exception e) {  
  8.             e.printStackTrace();  
  9.         }  

 Student2类中没有属性username2323

报错信息:

Xml代码  java 中容易误解的地方
  1. org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "username2323" (Class tv_mobile.Student2), not marked as ignorable  
  2.  at [Source: [email protected]; line: 1, column: 18] (through reference chain: tv_mobile.Student2["username2323"])  
  3.     at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)  

 

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

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

 

作者:黄威