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

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

问题描述

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

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

如果我将字段定义为整数,那么会如果我要从DB检索超过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!?

提前致谢。

推荐答案

整数是一个更好的选择,因为它可以处理 null ;对于 int null 将成为 0 ,默默地,如果使用了resultSet.getInt(..)。否则,它可能会抛出一些异常,例如无法将 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".

这里的表现很少受到关注。

Performance is of little concern here.


  • 如果选择 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天全站免登陆