要“归零”或者不是“null”我班级的属性 [英] To "null" or not to "null" my class's attributes
问题描述
当我用Java编写类时,我喜欢初始化直接设置为默认值的属性和构造函数中调用者设置的属性,如下所示:
When I write a class in Java, I like to initialize the attributes which are set to a default value directly and attributes which are set by the caller in the constructor, something like this:
public class Stack<E> {
private List<E> list;
private int size = 0;
public Stack(int initialCapacity) {
list = new ArrayList<E>(initialCapacity);
}
// remainder omitted
}
现在假设我有一个Tree类:
Now suppose I have a Tree class:
public class Tree<E> {
private Node<E> root = null;
// no constructor needed, remainder omitted
}
我应该将root属性设置为null,以标记它默认设置为null,或者省略空值吗?
Shall I set the root attribute to null, to mark that it is set to null by default, or omit the null value?
编辑:
在阅读 LinkedList 和 ArrayList ,它们都清楚地将它们的属性(LinkedList中的大小和ArrayList中的firstIndex / lastIndex)设置为0.
I came up with that idea after reading the sources of LinkedList and ArrayList, which both clearly set their attributes (size in LinkedList and firstIndex/lastIndex in ArrayList) to 0.
推荐答案
没有需要将引用类型属性显式初始化为 null
。默认情况下,它将初始化为null。类似地,基元类型有默认初始化规则:
There is no need to explicitly initialize a reference-typed attribute to null
. It will be initialized to null by default. Similarly, there are default initialization rules for the primitive types:
- 布尔属性初始化为
false
,和 - 积分(包括
char
),浮动
和double
属性都被初始化为零。
- boolean attributes are initialized to
false
, and - integral (including
char
),float
anddouble
attributes are all initialized to zero.
因此初始化<$在示例中c $ c> size 也是完全没必要的。
So the initialization of size
in the example is also strictly unnecessary.
因此,无论你是做还是做,这都是风格问题不初始化它们。我个人认为它不会提高可读性,因此浪费时间。 (我不会编写我的代码,由不了解Java基础知识的人维护...)
It is therefore purely a matter of style as to whether you do or do not initialize them. My personal opinion is that it does not improve readability, and therefore is a waste of time. (I don't write my code to be maintained by people who don't understand the basics of Java ...)
这篇关于要“归零”或者不是“null”我班级的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!