简体   繁体   English

何时使用包装类和原始类型

[英]When to use wrapper class and primitive type

When I should go for wrapper class over primitive types?什么时候我应该选择原始类型的包装类? Or On what circumstance I should choose between wrapper / Primitive types?或者在什么情况下我应该在包装器/原始类型之间进行选择?

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.将对象初始化为null或将null参数发送到方法/构造函数以指示状态或函数可能很方便。 This can't be done with primitives.这不能用原语来完成。

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设置场景,这比一些任意的错误对程序员更友好。

Generally, you should use primitive types unless you need an object for some reason (eg 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 article demonstrates how auto-boxing can cause a large performance difference. 文档建议这样做,本文演示了自动装箱如何导致巨大的性能差异。

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.在第一种情况下,您不能保持 SSN 值未初始化。 It may hurt if you are not checking if the value was set before you attempt to use it.如果您在尝试使用它之前没有检查该值是否已设置,则可能会受到伤害。

In the second case, you can keep SSN initialized with null.在第二种情况下,您可以将 SSN 初始化为 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.这可能会导致 NullPointerException,但它比在不初始化 SSN 字段的情况下尝试使用它时不知不觉地将默认值(零)作为 SSN 插入到数据库中要好。

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.而且,您会损失内存使用开销和装箱/拆箱时间。

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类型变量的服务类

  1. 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如果变量是long类型 - 当未初始化时,它将被设置为 0 - 这将在 GUI 中显示时让用户感到困惑
  2. If the variable is of type Long - when not initialized, it will be set to null - this null value won't show up in 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)。

Collections are the typical case for the simple Java wrapper objects.集合是简单 Java 包装器对象的典型情况。 However, you might consider giving the Wrapper a more specific meaning in the code (value object).但是,您可能会考虑在代码(值对象)中为 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.如果代码也易于理解,那么理解性能问题也可能更容易。

performance of 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 以表示这一点,但根据场景,这可能是不正确的或误导性的。

If you want to use Collections, you must use 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.但请记住,包装器是对象,因此您可以获得所有花哨的 Java 功能。 For example, you can use reflexion to create Integer objects, but not int values.例如,您可以使用反射来创建 Integer 对象,但不能使用 int 值。 Wrapper classes also have methods such as valueOf.包装类也有诸如 valueOf 之类的方法。

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.当原始类型(在我的示例中为字符串)定义相等时,您将需要覆盖相等。

Primitive values in Java are not object. Java 中的原始值不是对象。 In order to manipulate these values as object the java.lang package provides a wrapper class for each of the primitive data type.为了将这些值作为对象进行操作,java.lang 包为每个原始数据类型提供了一个包装类。

All Wrapper classes are final.所有 Wrapper 类都是最终的。 The object of all wrapper classes that can be initiated are immutable that means the value in the wrapper object can not be changed.可以启动的所有包装类的对象都是不可变的,这意味着包装对象中的值不能改变。

Although, the void class is considered a wrapper class but it does not wrap any primitive values and is not initiable.虽然void类被认为是一个包装类,但它不包装任何原始值并且不可初始化。 It does not have public constructor, it just denotes a class object representing the keyword void.它没有公共构造函数,它只是表示一个表示关键字 void 的类对象。

When to Use Primitive Types何时使用原始类型

  • When doing a large amount of calculations, primitive types are always faster — they have much less overhead.在进行大量计算时,原始类型总是更快——它们的开销要少得多。
  • When you don't want the variable to be able to be null.当您不希望变量能够为空时。
  • When you don't want the default value to be null.当您不希望默认值为 null 时。
  • If the method must return a value如果方法必须返回一个值

When to Use Wrapper Class何时使用包装类

  • When you are using Collections or Generics — it is required当您使用集合或泛型时 - 它是必需的
  • If you want the MIN_SIZE or MAX_SIZE of a type.如果你想要一个类型的 MIN_SIZE 或 MAX_SIZE。
  • When you want the variable to be able to be null.当您希望变量能够为空时。
  • When you want to default value to be null.当您希望默认值为 null 时。
  • If sometimes the method can return a null value.如果有时该方法可以返回空值。

from https://medium.com/@bpnorlander/java-understanding-primitive-types-and-wrapper-objects-a6798fb2afe9来自https://medium.com/@bpnorlander/java-understanding-primitive-types-and-wrapper-objects-a6798fb2afe9

When to Use Primitive Types When doing a large amount of calculations, primitive types are always faster — they have much less overhead.何时使用原始类型在进行大量计算时,原始类型总是更快——它们的开销要少得多。

When you don’t want the variable to be able to be null.

When you don’t want the default value to be null.

If the method must return a value

When to Use Wrapper Class何时使用包装类

When you are using Collections or Generics — it is required当您使用集合或泛型时 - 它是必需的

If you want the MIN_SIZE or MAX_SIZE of a type.如果你想要一个类型的 MIN_SIZE 或 MAX_SIZE。

When you want the variable to be able to be null.当您希望变量能够为空时。

When you want to default value to be null.当您希望默认值为 null 时。

If sometimes the method can return a null value.如果有时该方法可以返回空值。

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

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