简体   繁体   English

我应该定义 class 属性原语(如果可能的话)还是应该使用包装器 class?

[英]Should I define class attributes primitives (when it's possible) or should I use a Wrapper class?

I am wondering if it's recommended always to use primitive types such as int when defining class attributes or should I wrapper classes instead of.我想知道在定义 class 属性时是否建议始终使用诸如 int 之类的原始类型,或者我应该包装类而不是。

class Test{
    private final int id;

    /**
     * Class constructor
     * @param id
     */
    Test(int id) {
      this.id = id;
    }
  }

It depends on what you need to do... If it's important to you to hold null values so you should use wrappers... Else you could as well use primitive... If you don't know if you need null or not then it's better to use primitives to avoid getting NPE.这取决于您需要做什么...如果保存 null 值对您很重要,那么您应该使用包装器...否则您也可以使用原始...如果您不知道是否需要 null那么最好使用原语来避免获得NPE。

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

相关问题 当不使用某些属性时,我应该在我的包装器 class 或 null 中使用 Java 8 的 Optional 吗? - Should I use Java 8's Optional in my wrapper class or null when not using some attributes? 我什么时候应该在 class 中使用“this”? - When should I use "this" in a class? 我是否应该定义一个空类,以便可以将其用作泛型 - Should I define an empty class so that I can use it as a generic 我什么时候应该使用MapMaker类的weakValues()? - When should I use weakValues() of the MapMaker class? 我什么时候应该使用原语而不是包装对象? - When should I use primitives instead of wrapping objects? 在 class 中引用 static 字段时,我应该使用 class 名称吗? - Should I use a class name when referencing a static field in that class? 什么时候应该使用泛型参数,什么时候应该使用父类作为参数 - When should I use a generic parameter and when should I use parent class as a parameter 我是否应该将构造函数定义为扩展抽象类的类? - Should I define a constructor is a class that extends an abstract class? 我应该在Android的Date中使用哪个类? - What class should I use for Date's in Android? 当只有一个实现类时,为什么要使用接口? - Why should I use an interface when there is only one implementation class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM