使用哪一个,int 或 Integer [英] Which one to use, int or Integer

查看:29
本文介绍了使用哪一个,int 或 Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个数据传输对象,用于存储从数据库中检索到的记录.在这个数据传输对象中,我需要声明一个数字字段.对于哪个更好 - intInteger

I need to create a data transfer object, which I will use for storing the records retrieved from database. In this data transfer object, I need to declare a numeric field. For that which one is better - int or Integer

如果我将字段定义为整数,如果我要从数据库中检索超过 2000 条记录,是否会因为整数"类型而对性能产生任何影响!?

If I am defining the field as Integer, will there be any performance impact because of 'Integer' type if I am going to retrieve more than 2000 records from DB!?

提前致谢.

推荐答案

Integer 是更好的选择,因为它可以处理null;对于 int,如果使用 resultSet.getInt(..)null 将变为 0,静默.否则,它可能会抛出一些异常,例如无法将 null 设置为原始属性".

Integer is a better option, as it can handle null; for int, null would become 0, silently, if resultSet.getInt(..) is used. Otherwise, it might throw some exception, something like, "Unable to set null to a primitive property".

性能在这里无关紧要.

  • 如果你选择int,你最终会添加额外的处理代码;这对你没有多大好处.您的代码将不会干净和直接,会有很多样板代码,您甚至不会获得性能.
  • 让我说清楚,对于数据库,null 与零不同.有时您最终会输入 0,其中 null 是本意.想象一下用户提交了一个表单,并且没有为 int 提供任何值的情况.默认情况下,您最终会获得 0.当该字段在数据库中 not null 时,这是有道理的,或者确实如此.
  • if you choose int, you will end-up adding extra handling code; and that wouldn't benefit you much. Your code will not be clean and straight-forward, lot of boiler-plate code, and you wouldn't even gain performance.
  • let me make it clear, for databases, null is not same as zero. Sometimes you end-up entering 0, where null was intended. Imagine the case where user submitted a form, and doesn't supply any value for int. You will end up getting 0 by default. It makes sense, or does that really, when that field is not null in the database.

这篇关于使用哪一个,int 或 Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆