Java 使用哪一个,int 或 Integer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/423704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Which one to use, int or Integer
提问by Veera
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 - intor Integer
我需要创建一个数据传输对象,用于存储从数据库中检索到的记录。在这个数据传输对象中,我需要声明一个数字字段。对于哪个更好 - int或Integer
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!?
如果我将字段定义为整数,如果我要从数据库中检索超过 2000 条记录,是否会因为“整数”类型而对性能产生任何影响!?
Thanks in advance.
提前致谢。
采纳答案by Adeel Ansari
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".
Integer
是更好的选择,因为它可以处理null
;for int
,null
会变成0
, 默默地,如果resultSet.getInt(..)
被使用。否则,它可能会抛出一些异常,例如“无法设置null
为原始属性”。
Performance is of little concern here.
性能在这里无关紧要。
- 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
, wherenull
was intended. Imagine the case where user submitted a form, and doesn't supply any value forint
. You will end up getting0
by default. It makes sense, or does that really, when that field isnot null
in the database.
- 如果您选择
int
,您最终将添加额外的处理代码;这对你没有多大好处。你的代码不会干净和直接,会有很多样板代码,你甚至不会获得性能。 - 让我说清楚,对于数据库,null 与零不同。有时,您最终会进入
0
,null
预期的位置。想象一下用户提交了一个表单,并且没有为 提供任何值的情况int
。你最终会得到0
默认。当该字段not null
在数据库中时,这是有道理的,或者确实如此。
回答by Mehrdad Afshari
Integer
is theoretically slower than int
, however the performance impact should be minimal unless you are crunching numbers. Also JIT optimizations will reduce the performance loss.
Integer
理论上比 慢int
,但是除非您处理数字,否则性能影响应该很小。此外,JIT 优化将减少性能损失。
Use the one that better suits your situation in terms of primitive or reference type.
在原始类型或引用类型方面使用更适合您的情况的一种。
回答by agnul
I guess it depends among other things on what you are using for accessing the database. With plain old JDBC you could do with int
s, while an ORM could silently convert them to Integers
anyway. And Integer would allow you to handle nulls.
我想这取决于您用于访问数据库的内容。使用普通的旧 JDBC,您可以使用int
s,而 ORM 可以默默地将它们转换为Integers
无论如何。Integer 将允许您处理nulls。
回答by tddmonkey
You should really make your decision based on- what you need your object to do, rather than the performance costs. Deciding based on performance should be done, once a speed issue has been identified with a profiler - the root of all evil and all that.
你真的应该根据你需要你的对象做什么来做出你的决定,而不是性能成本。一旦使用分析器确定了速度问题,就应该根据性能做出决定——这是万恶之源等等。
Look at some of the features of both and use that for your decision, e.g.
查看两者的一些功能并将其用于您的决定,例如
Integer
can benull
,int
cannot. So is theint
in the DBaNullable
field?- Do you need access to the
Integer
class methods? - Are you doing arithmetic?
Integer
可以null
,int
不能。那么int
在数据库中是一个Nullable
字段吗?- 您需要访问
Integer
类方法吗? - 你在做算术吗?
Personally, I always opt for the primitive over the wrapper. But that's just a preference thing, rather than based on any technical merit.
就个人而言,我总是选择原始而不是包装器。但这只是一种偏好,而不是基于任何技术优点。
回答by Andrzej Doyle
To my mind, the choice between declaring something as int or Integer simply comes down to whether null is a valid value for it or not. Autoboxing (and autounboxing) will take care of any conversion issues where the number simply must be one type or another. Performance (as has been pointed out) is also unlikely to be noticable in almost all cases.
在我看来,将某物声明为 int 还是 Integer 的选择简单归结为 null 是否是它的有效值。自动装箱(和自动拆箱)将处理任何转换问题,其中数字必须是一种或另一种类型。在几乎所有情况下,性能(正如已经指出的那样)也不太可能引人注目。
Besides, int should be the natural choice, and is likely to be the most performant should that be an issue anyway. If you need to be able to store nulls, then you haveto use Integer (and also ensure that no null references are auto-unboxed for a method that takes simply ints as this will result in a NullPointerException).
此外, int 应该是自然的选择,并且无论如何都可能是性能最高的。如果您需要能够存储空值,那么您必须使用 Integer(并确保没有空引用被自动拆箱用于仅采用整数的方法,因为这将导致 NullPointerException)。
回答by Peter Lawrey
To give you an idea, 2000 Integer would add about 0.5 ms to you query. If you have to serialize this data it could add quite a bit more.
给你一个想法,2000 Integer 会给你的查询增加大约 0.5 毫秒。如果您必须序列化这些数据,它可能会添加更多。
However, correctness should come first. There is no point being very fast but wrong. You have to consider null values and how you handle them. (Unless the column is NOT NULL) You could use Integer.MIN___VALUE or you could use a longfield instead of int and use Long.MIN_VALUE for null. Even though it is larger than int, it would still be many times smaller and more efficient than Integer.
但是,正确性应该是第一位的。速度非常快是没有意义的,但这是错误的。您必须考虑空值以及如何处理它们。(除非该列不是 NULL)您可以使用 Integer.MIN___VALUE 或者您可以使用long字段而不是 int 并使用 Long.MIN_VALUE 为空。尽管它比 int 大,但它仍然比 Integer 小很多倍,效率也更高。
回答by Amine
int is 10x faster than integer
int 比整数快 10 倍
we test this code with jetm performance library
我们使用 jetm 性能库测试此代码
int n;
EtmPoint point1 = etmMonitor.createPoint("test:objects");
for (n = 0; n < 1000000; n++) {
Integer t = 0;
t = 10;
t = 11;
}
point1.collect();
EtmPoint point = etmMonitor.createPoint("test:primitives");
for (n = 0; n < 1000000; n++) {
int t = 0;
t = 10;
t = 11;
}
point.collect();
etmMonitor.render(new SimpleTextRenderer());
and the results:
test:objects 10.184
test:primitives 1.151
结果:
test:objects 10.184
test:primitives 1.151
回答by Deepak
int
can't be cast to the String
with using the toString
or (String)
.
int
不能String
使用toString
or强制转换为with (String)
。
Integer
can cast to String
with toString
or (String)
and it can handle null
.
Integer
可以投射到String
withtoString
或(String)
并且它可以处理null
.
回答by peterk
int
is used by java for most all calculations. Integer
is used in all forms of Collections except for primitive arrays.
int
由 java 用于大多数所有计算。 Integer
用于所有形式的集合,除了原始数组。
Using lots of temporary Integers with thrash the garbage collector and use unprofilable CPU in the background that will cause general slowdowns in everything. Too many temporaries being trashed per second will cause the CG to enter emergency "I need memory now" mode that can cause stalls in latency critical applications (ie: real time interactive graphics, physical device controllers or communications)
使用大量临时整数和垃圾收集器并在后台使用不可分析的 CPU,这将导致一切普遍放缓。每秒丢弃太多临时文件将导致 CG 进入紧急“我现在需要内存”模式,这可能导致延迟关键应用程序(即:实时交互式图形、物理设备控制器或通信)的停顿
So for me if I have a lot of nested calls that do no math but access a lot of collections such as using keys for maps I use Integer so as to avoid tons of auto boxing when arguments are passed.
所以对我来说,如果我有很多嵌套调用,它们不做数学运算但访问很多集合,例如使用映射的键,我使用 Integer 以避免在传递参数时大量自动装箱。
If the operations are math intensive or used as loop counters or other math oriented operations and not stored in collections (other than primitive arrays) I use the primitive. The same goes for all the other primitives except String which is a full fledged object.
如果操作是数学密集型的,或者用作循环计数器或其他面向数学的操作,而不是存储在集合中(原始数组除外),我将使用原语。除了 String 是一个完整的对象之外,所有其他原语也是如此。
回答by Pankaj Singla
If you want to check for a null
value then Integer
is best but if you want to compare the integer then int may be better. In the following example I am using integer c= 1000 and d= 1000 and compare it return false but in case of int they will return true.
如果你想检查一个null
值,那么Integer
最好,但如果你想比较整数,那么 int 可能更好。在下面的示例中,我使用整数 c=1000 和 d=1000 并比较它返回 false 但在 int 的情况下它们将返回 true。
public class IntegerCompare {
public static void main(String[] args) {
int a = 1000;
int b = 1000;
Integer c = 1000;
Integer d = 1000;
if (a == b) {
System.out.println("int Value Equals");
}
if (c == d) {
System.out.println("Integer value Equals");
} else {
System.out.println("Integer Value Not Equals");
}
}
}