要“归零”或者不是“null”我班级的属性

编程入门 行业动态 更新时间:2024-10-17 19:23:54
本文介绍了要“归零”或者不是“null”我班级的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我用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 and double attributes are all initialized to zero.

因此初始化 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”我班级的属性

本文发布于:2023-11-13 02:15:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583139.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:班级   属性   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!