java 中容易误解的地方

本文探讨了Java中不同类型间的转换技巧,特别是基本类型到包装类型的自动转换,并展示了如何正确处理JSON字符串与Java对象之间的映射,包括空JSON字符串的处理及属性不匹配时的异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 运行结果:

 

 

但是,如果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.youkuaiyun.com/hw1287789687

http://blog.youkuaiyun.com/hw1287789687/article/details/45916001

 

作者:黄威

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值