Java 何时使用包装类和原始类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1570416/
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
When to use wrapper class and primitive type
提问by Gopi
When I should go for wrapper class over primitive types? Or On what circumstance I should choose between wrapper / Primitive types?
什么时候我应该选择原始类型的包装类?或者在什么情况下我应该在包装器/原始类型之间进行选择?
采纳答案by pstanton
Others have mentioned that certain constructs such as Collections
require objects and that objects have more overhead than their primitive counterparts (memory & boxing).
其他人提到某些构造(例如Collections
需要对象)并且对象比它们的原始对应物(内存和装箱)具有更多的开销。
Another consideration is:
另一个考虑是:
It can be handy to initialize Objects to null
or send null
parameters into a method/constructor to indicate state or function. This can't be done with primitives.
将对象初始化为方法/构造函数null
或将null
参数发送到方法/构造函数以指示状态或函数可能很方便。这不能用原语来完成。
Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
许多程序员将数字初始化为 0(默认值)或 -1 以表示这一点,但根据场景,这可能是不正确的或误导性的。
This will also set the scene for a NullPointerException
when something is being used incorrectly, which is much more programmer-friendly than some arbitrary bug down the line.
NullPointerException
当某些东西被错误使用时,这也将设置场景,这比一些任意的错误更对程序员友好。
回答by Tom
If you want to use Collections, you mustuse Wrapper classes.
如果要使用集合,则必须使用 Wrapper 类。
Primitive types, are used for arrays. Also, to represent data that has no behaviour,for example, a counter, or a boolean condition.
原始类型,用于数组。此外,表示没有行为的数据,例如,计数器或布尔条件。
Since autoboxing, the "when to use primitive or wrapper" frontier has become quite fuzzy.
自从自动装箱以来,“何时使用原语或包装器”的边界变得非常模糊。
But remember, Wrappers are objects, so you get all the fancy Java features. For example, you can use reflexion to create Integer objects, but not int values. Wrapper classes also have methods such as valueOf.
但请记住,包装器是对象,因此您可以获得所有花哨的 Java 功能。例如,您可以使用反射来创建 Integer 对象,但不能使用 int 值。包装类也有诸如 valueOf 之类的方法。
回答by Matthew Flaschen
Generally, you should use primitive types unless you needan object for some reason (e.g. to put in a collection). Even then, consider a different approach that doesn't require a object if you want to maximize numeric performance. This is advised by the documentation, and this articledemonstrates how auto-boxing can cause a large performance difference.
通常,除非出于某种原因(例如放入集合)需要一个对象,否则您应该使用原始类型。即便如此,如果您想最大化数字性能,请考虑一种不需要对象的不同方法。这是通过建议的文件,以及本文演示了自动装箱如何能引起较大的性能差异。
回答by Chris Missal
If you want to create a value type. Something like a ProductSKU or AirportCode.
如果要创建值类型。类似于 ProductSKU 或 AirportCode 的东西。
When a primitive type (string in my examples) defines equality, you'll want to override equality.
当原始类型(在我的示例中为字符串)定义相等时,您将需要覆盖相等。
回答by jjnguy
I would only use the wrapper types if you have to.
如果必须,我只会使用包装器类型。
In using them you don't gain much, besides the fact that they are Objects
.
在使用它们时,除了它们是Objects
.
And, you lose overhead in memory usage and time spent boxing/unboxing.
而且,您会损失内存使用开销和装箱/拆箱时间。
回答by Mattias Holmqvist
Collections are the typical case for the simple Java wrapper objects. However, you might consider giving the Wrapper a more specific meaning in the code (value object).
集合是简单 Java 包装器对象的典型情况。但是,您可能会考虑在代码(值对象)中为 Wrapper 赋予更具体的含义。
IMHO there's almost always a benefit to use value objects when it boils down to readability and maintainance of the code. Wrapping simple data structures inside of objects when they have certain responsibilities often simplifies the code. This is something that is very important in Domain-Driven Design.
恕我直言,当归结为代码的可读性和可维护性时,使用值对象几乎总是有好处的。当对象具有某些职责时,将简单的数据结构包装在对象内部通常可以简化代码。这在领域驱动设计中非常重要。
There is of course the performance issue, but I tend to ignore that until I have the possibility to measure the performance with proper data and do more directed actions towards the problematic area. It might also be easier to understand the performance issue if the code is easy to understand as well.
当然存在性能问题,但我倾向于忽略这一点,直到我有可能用适当的数据衡量性能并对有问题的区域采取更直接的行动。如果代码也易于理解,那么理解性能问题也可能更容易。
回答by Cody
In my opinion, if my class members are wrapper variables, it does not rely on default values, which is developer friendly behavior.
在我看来,如果我的类成员是包装变量,它不依赖于默认值,这是开发人员友好的行为。
1.
1.
class Person {
int SSN ; // gets initialized to zero by default
}
2.
2.
class PersonBetter {
Integer SSN; //gets initialized to null by default
}
In the first case, you cannot keep SSN value uninitialized. It may hurt if you are not checking if the value was set before you attempt to use it.
在第一种情况下,您不能保持 SSN 值未初始化。如果您在尝试使用它之前没有检查该值是否已设置,则可能会受到伤害。
In the second case, you can keep SSN initialized with null. Which can lead to NullPointerException but it is better than unknowingly inserting default values(zero) as SSN into to the database whenever you attempt to use it without initializing SSN field.
在第二种情况下,您可以将 SSN 初始化为 null。这可能会导致 NullPointerException,但它比在不初始化 SSN 字段的情况下尝试使用它时不知不觉地将默认值(零)作为 SSN 插入到数据库中要好。
回答by loknath
performanceof applications that are dominated by numerical calculations can benefit greatly from the use of primitives.
由数值计算主导的应用程序的性能可以从基元的使用中大大受益。
primitive types,one uses the == operator, but for wrapper the preferred choice is to call the equals() method.
原始类型,使用 == 运算符,但对于包装器,首选是调用 equals() 方法。
"Primitive types considered harmful"because they mix "procedural semantics into an otherwise uniform object-oriented model.
“原始类型被认为是有害的”,因为它们将“过程语义”混合到其他统一的面向对象模型中。
Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
许多程序员将数字初始化为 0(默认值)或 -1 以表示这一点,但根据场景,这可能是不正确的或误导性的。
回答by Mohamed Afzal
Practically I had encountered a situation where use of wrapper class can be explained.
实际上,我遇到过可以解释包装类使用的情况。
I created a service class which had a long
type variable
我创建了一个具有long
类型变量的服务类
- If the variable is of type
long
- when not initialized, it will be set to 0 - this will be confusing to the user when displayed in GUI - If the variable is of type
Long
- when not initialized, it will be set tonull
- this null value won't show up in GUI.
- 如果变量是类型
long
- 当未初始化时,它将被设置为 0 - 这将在 GUI 中显示时让用户感到困惑 - 如果变量的类型
Long
- 当未初始化时,它将被设置为null
- 此空值不会显示在 GUI 中。
This applies to Boolean
as well where values can be more confusing when we use primitive boolean
(as default value is false).
这也适用于Boolean
当我们使用原始boolean
值(因为默认值为 false)时值可能更容易混淆的地方。
回答by Ahmad Sayeed
Primitive values in Java are not object. In order to manipulate these values as object the java.lang package provides a wrapper class for each of the primitive data type.
Java 中的原始值不是对象。为了将这些值作为对象进行操作,java.lang 包为每个原始数据类型提供了一个包装类。
All Wrapper classes are final. The object of all wrapper classes that can be initiated are immutable that means the value in the wrapper object can not be changed.
所有 Wrapper 类都是最终的。可以启动的所有包装类的对象都是不可变的,这意味着包装对象中的值不能改变。
Although, the voidclass is considered a wrapper class but it does not wrap any primitive values and is not initiable. It does not have public constructor, it just denotes a class object representing the keyword void.
虽然void类被认为是一个包装类,但它不包装任何原始值并且不可初始化。它没有公共构造函数,它只是表示一个表示关键字 void 的类对象。