Tag: 初始化

我可以使用Java中的相同指令声明和初始化数组吗?

有没有办法同时做以下事情? static final int UN = 0; // uninitialized nodes int[] arr; // … code … arr = new int[size]; for (int i = 0; i < 5; i++) { arr[i] = UN; } 基本上,我想知道arr一旦我知道它的大小将是什么并初始化为UN而不必循环。 所以这样的事情: int[] arr = new int[size] = UN; 这可能吗? 谢谢。

Java错误:新的通用TreeNode数组

我有TreeNode的generics类: public class TreeNode { public E key; public int num_of_children; public TreeNode [] children; public TreeNode(int num_of_children) { this.num_of_children = num_of_children; children = new TreeNode[num_of_children];// Why not: new TreeNode[num_of_children]? } public TreeNode clone() { TreeNode node = new TreeNode(num_of_children); return node; } } 当我尝试这样做时: children = new TreeNode [num_of_children]; 我收到错误。 但“新的TreeNode [num_of_children]”有效。 我读到了类型擦除,我不明白为什么TreeNode[]不起作用。 这是为什么? […]

什么是subClass sc = new subClass()和superClass sc = new subClass之间的区别?

class superClass {} class subClass extends superClass{} public class test { public static void main() { superClass sc1 = new subClass(); subClass sc2 = new subClass(); //whats the difference between the two objects created using the above code? } }

定义初始化与构造函数初始化

在Java中,但在其他OO语言中,在其定义中初始化属性之间存在差异,如 class Example { public Sample sample_attribute = new Sample(); } 并使用构造函数初始化它? class Example { public Sample sample_attribute; public Example() { sample_attribute = new Sample(); } } 我想不出任何实际的区别,有吗? 否则,是否存在一种方法比另一种方法更好的情况,即使它们具有相同的结果?

在定义字段之前无法引用字段,但仅限于您不符合条件

我发现发生以下代码使我的下巴下降: public class MCVE { { // instance initializer System.out.println(test); // cannot reference a field before it is defined System.out.println(this.test); } private final String test = “wat”; } System.out.println(test);行System.out.println(test); 给出错误 在定义之前无法引用字段。 但是行System.out.println(this.test); 不是 当我符合条件时,为什么这不是错误?

基元的默认值

在Java中,如果未初始化int类型的变量将保留什么(我知道如果我在初始化之前直接使用x ,它将不会让我编译)? 说,如果我这样做: int x; 怎么样 int[] x; 谢谢

如何从java中的静态初始化块返回

我想从静态块返回。 看起来return和break语句不起作用。 有没有其他选择。 我知道糟糕的解决方法可能是创建一个标志并检查标志是否继续。 我知道初始化块不是用于进行计算,而是用于在类加载期间进行基本初始化。

访问枚举构造函数中的其他枚举

我需要类似以下的东西 enum EE { A(“anything”), B(“beta”), … Z(“zulu”), ALL, ; EE(String s) { this.s = s; } EE() { String s = “”; for (EE ee : values()) { // PROBLEM HERE if (ee != ALL) s += ” ” + ee.s; } this.s = s; } } 创建ALL我想访问枚举的其他成员。 由于values()返回null ,因此上述操作null 。 使用A , B […]

Java实例变量用方法初始化

我对下面这段代码感到有点困惑: public class Test{ int x = giveH(); int h = 29; public int giveH(){ return h; } public static void main(String args[]) { Test t = new Test(); System.out.print(tx + ” “); System.out.print(th); } } 这里的输出是0 29 ,但我认为这必须是编译器错误,因为当涉及方法giveH()时,变量h应该尚未初始化。 那么,编译是从上到下进行的吗? 这为何有效? 为什么x 0的值不是29?

如何在Spring中控制bean init-method调用的顺序?

假设我有bean,应该在另一个bean的init-method之后调用init-method或constructor。 可能吗?