java初学者:初始化类变量

发布于 2024-10-06 11:22:09 字数 1077 浏览 6 评论 0原文

我刚刚阅读了SUN java代码约定;顺便说一句,非常好的文件。我读过这个

6.3 初始化: 尝试在声明局部变量的地方对其进行初始化。不初始化的唯一原因 声明变量的位置是初始值是否取决于首先发生的某些计算。

我想知道类变量是否有相同的建议,例如我有:

public class NNmatrix {

    protected ArrayList<ArrayList<Double>> matrix;     // line 1
    public NNmatrix() {
        matrix = new ArrayList<ArrayList<Double>>();     // line 2
    }
    /**
     * 
     * @param otherMtrx
     */
    public NNmatrix(final ArrayList<ArrayList<Double>> otherMtrx) {
        final int rows = otherMtrx.size();
        matrix = new ArrayList<ArrayList<Double>>(rows);  // line3
        for (int i = 0; i < rows; i++) {
            this.matrix.add(new ArrayList<Double>(otherMtrx.get(i)));
        }
    }
}

编辑代码#如果我要初始化声明它的变量(在类中),我会删除“第2行”并保留“第3行”,因为如您所知,内存中保留(行)的性能问题。

问题是:

  1. 这样做是一个好的实践或初始化问题仅适用于方法等内部的局部变量吗?
  2. 如果可以的话,我想知道如果我编辑代码#初始化@第3行或初始化@第1行,哪个会先出现?

I've just read the SUN java code conventions; very nice document btw. And I've read this

6.3
Initialization:
Try to initialize local variables where they’re declared. The only reason not to initialize a
variable where it’s declared is if the initial value depends on some computation occurring first.

And I was wondering if Class variables are having same suggestion or not, for example I have:

public class NNmatrix {

    protected ArrayList<ArrayList<Double>> matrix;     // line 1
    public NNmatrix() {
        matrix = new ArrayList<ArrayList<Double>>();     // line 2
    }
    /**
     * 
     * @param otherMtrx
     */
    public NNmatrix(final ArrayList<ArrayList<Double>> otherMtrx) {
        final int rows = otherMtrx.size();
        matrix = new ArrayList<ArrayList<Double>>(rows);  // line3
        for (int i = 0; i < rows; i++) {
            this.matrix.add(new ArrayList<Double>(otherMtrx.get(i)));
        }
    }
}

EDITING CODE# If I would initialize the variable where it's declared (in class), I would remove "line 2" and leave "line 3" because performance issue# reserving (rows) in memory as you know.

The question is:

  1. Is doing that a good practice or initialization matter only apply for local variables inside methods etc only?
  2. If it's fine, I want to know which will come first if I did the EDITING CODE# the initialization @ line 3 or initialization @ line 1 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

荒芜了季节 2024-10-13 11:22:09

这些是实例变量,而不是类变量。实例变量属于特定对象,类变量则不属于(抱歉挑剔)。

我认为在声明变量的地方初始化变量更简单且更易于阅读。

jvm从文件顶部开始初始化实例变量和实例初始化块,然后向下工作,只有在初始化所有变量并运行初始化块之后,它才会执行构造函数。

These are instance variables, not class variables. Instance variables belong to a specific object, class variables don't (sorry to nitpick).

I think initializing the variable where it's declared is simpler and easier to read.

The jvm starts initializing instance variables and instance initializer blocks at the top of the file and works its way down, only after it has initialized all the variables and run the initializer blocks does it execute the constructor.

旧时模样 2024-10-13 11:22:09

您引用的行仅指局部变量。因为在 Java 中,局部变量不需要在作用域的顶部声明,而是可以在使用之前在任何地方声明,所以它很有意义。

对于类和实例变量,我个人的偏好是在声明变量的地方对其进行初始化。在许多情况下,除了默认构造函数之外,我没有任何其他构造函数,这消除了编写默认构造函数的需要,因为编译器将自动提供一个。我发现这可以清理并缩短我的代码。

在您提供的第二种情况构造函数中,您可以为构造函数中的初始化提供一个很好的案例。

对于类变量,我发现有几次我想在实例化块中初始化而不是在声明中内联。

The line you quoted refers only to local variables. Because in Java local variables don't need to be declared at the top of the scope but can be declared anywhere before they are used, it makes a lot of sense.

For class and instance variables, my personal preference is to initialize the variable where it is declared. In many cases where I don't have any other constructors than the default this removes the need to have a default constructor written as the compiler will automatically provide one. I find this cleans up and shortens my code.

In the second case constructor you provided you can make a good case for initializing in the constructor.

With class variables I have found few times where I would want to initialize in the instantiation block instead of inline at the declaration.

可可 2024-10-13 11:22:09

我主张让你的代码保持原样。

虽然一般来说我确实喜欢在声明时初始化实例变量,但当我必须在某些构造函数中重新初始化它们时,我不喜欢这样做。我更喜欢在声明处初始化,或者在每个构造函数路径中初始化(也许只是在每个其他构造函数调用的单个构造函数中)。纯声明表明正在发生更复杂的事情,而将最简单的初始化移至声明可以隐藏这一点。

I would argue for leaving your code the way it is.

While in general I do like to initialize instance variables at the declaration, I do not like to do so when I must re-initialize them in some constructor. I prefer to either initialize at the declaration, or in every constructor-path (perhaps just in a single constructor called by every other constructor). The pure declaration signals that something more complicated is going on, while moving the simplest initialization to the declaration can hide that.

静若繁花 2024-10-13 11:22:09

您有几个不同的选项,可能都属于微优化。通常,这些类型的优化很少被关注,除非您在并发环境中使用静态变量或执行诸如池类之类的时髦操作。

  1. 没有理由不能在构造函数或其他类似于概述的方法中初始化变量这里。就我个人而言,我更喜欢尽可能在声明时初始化变量。

  2. 根据我的理解,如果发生在构造函数中和声明中,初始化将大致同时发生。我从来没有必要知道在实践中哪个实际上是最先发生的,但你可以做一个简单的 System.out 测试来找出答案。

You have a couple different options that probably all fall under micro-optimizations. Typically these types of optimizations are of little concern unless you are working with static variables in a concurrent environment or doing something funky like pooling classes.

  1. There's no reason why you cant initialize your variables in your constructor or other methods similar to what is outlined here. Personally, I prefer to initialize my variables at their declaration whenever possible.

  2. From my understanding, initialization will occur at roughly the same time if occurring in the constructor vs at declaration. I've never had to know which actually comes first in practice, but you could do a simple System.out test to find out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文