简体   繁体   English

Java 通用整数数据与原始整数数据

[英]Java generic Integer data vs primitive int data

I know that in Java we can use generic data types for various reasons.我知道在Java 中我们可以出于各种原因使用通用数据类型 However, in terms of data storage .但是,在数据存储方面 If a primitive int in Java can store up to 2,147,483,647 signed values, does this same storage capacity apply for the Integer generic type?如果 Java 中的原始int最多可以存储2,147,483,647 个有符号值,那么同样的存储容量是否适用于 Integer 泛型类型? Also, does the data type chosen in a program affect the runtime in any way?此外,程序中选择的数据类型是否会以任何方式影响运行时? Or does it more so affect the space-time complexity of a program?还是它对程序的时空复杂度的影响更大? My main question is that if I stick with a data type that is rather small but appropriate for my programs needs, than will it by any means help my program run faster?我的主要问题是,如果我坚持使用相当小但适合我的程序需要的数据类型,那么它是否会以任何方式帮助我的程序运行得更快?

Yes, the limitations are still there.是的,限制仍然存在。

You shouldn't treat Integer like this magical object, all it is is an object that holds an int called value .您不应该将Integer视为这个神奇的对象,它只是一个包含名为valueint的对象。 So, without auto-boxing and unboxing, you could technically create your own Integer wrapper class.因此,无需自动装箱和拆箱,您可以在技术上创建自己的Integer包装器类。 What to take away is Integer is pretty much the exact same as int , except it's an object.要带走的是Integer几乎与int完全相同,只是它是一个对象。

About your main question about the speed, Integer is just a tiny bit slower, but I don't think you should worry about it.关于你对速度的主要问题, Integer只是稍微有点慢,但我不认为你应该担心。 It's only slower because Objects need to be allocated in the heap space.它只是更慢,因为需要在堆空间中分配Objects

Yes, the same limitations apply.是的,同样的限制适用。

You can see the source of the Integer class here:您可以在此处查看 Integer 类的来源:

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Integer.java http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Integer.java

Line 840 shows that an Integer is backed by a simple int :第 840 行显示一个 Integer 由一个简单的int支持:

private final int value;

So whatever restrictions an int has, an Integer also has.所以无论int有什么限制, Integer也有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM