java - java 中的约定 - 构造函数/方法之外的 "new"?

标签 java new-operator

简单的问题。有心友写过类似这样的代码(只是为了给你解释我的问题,一点用都没有....)

class Example{
    private int[] tab = new int[10];
    public Example() {
        for(int i = 0 ; i < 10 ; i++)
            tab[i] = (int)(Math.random()*100);
        for(int i = 0 ; i < 10 ; i++)
            System.out.println(tab[i]);
    }
    public static void main(String[] arg) {
        Example ex = new Example();
    }
}

我告诉他他应该将 new 放在构造函数中

class Example{
    private int[] tab;
    public Example() {
        tab = new int[10];
    ...
}

当他问我为什么时,我不知道该怎么回答:除了“这样更好”之外,我没有明确的论据。按照我的学习方式,您可以使用基本类型(int、double...)初始化变量,但对于数组,您应该在构造函数中进行初始化。

所以:

  • 真的更好吗?
  • 是否有一些充分的理由:惯例、风格?
  • 它是否会改变任何东西,比如使用更少/更多内存?

我没有考虑元素数量可以变化的情况。永远是 10

最佳答案

  • is it really better ?

不是真的,IMO。

  • is there some good reasons : convention ? style ?

当您有多个构造函数时,或者当初始值取决于构造函数参数时,选择一种方式而不是另一种方式可能有正当理由;例如

private int[] tab;

public Example(int size) {
    tab = new int[size];
    for (int i = 0; i < size; i++)
        tab[i] = (int) (Math.random() * 100);
}

private int[] tab = new int[10];

public Example(int initial) {
    for (int i = 0; i < 10; i++)
        tab[i] = initial;
}

public Example() {
    for (int i = 0; i < 10; i++)
        tab[i] = (int) (Math.random() * 100);
}

除此之外(在您的示例中),没有关于此的一般规则。这是个人品味的问题。

  • does it change anything like less/more memory used ?

在您的示例中,这没有任何区别。通常,代码大小或性能可能存在微小差异,但不值得担心。

总之,我不认为你对你 friend 的建议有合理的依据。

The way I learn it, you can initialize variables with basic types (int, double...) but for arrays you should do it in the constructor.

您应该忘却这一点……或者至少认识到这只是个人喜好。

关于java - java 中的约定 - 构造函数/方法之外的 "new"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3830260/

相关文章:

java - 什么是 Spring 的注解对应物 <context :property-override>?

java - 如何在 10 位数字的第三位和下一个第三位和下一个第四位显示带点的数字?

c++ - 我相信这是 clang 中的一个错误,与构造函数抛出的放置新表达式有关

java - 静态与新对象

java.sql.SQLException : Invalid value for getShort() - ' '

java - 为 Thread 类中的 start0() 本地方法加载本地代码库

java - Eclipse equals() 模板,其中 null String == empty String

c++ - 为什么重载的新运算符是隐式静态的,并且构造对象不需要范围解析

c++ - 为什么这个析构函数不必删除类对象?

python - 问候程序