使用和不使用`New`关键字定义数组之间有什么区别? [英] What is the difference between using and not using `New` keyword to define an array?
问题描述
看看这两个简单的程序:
Look at this two simple program :
程序1:
public class GenArray extends Applet {
byte[] myArray ={ (byte) 'M', (byte) 'o', (byte) 'd', (byte) 'e',
(byte) '1' };
}
程序2:
public class GenArray extends Applet {
byte[] myArray = new byte[5];
{
myArray[0] =(byte) 'M';
myArray[1] =(byte) 'o';
myArray[2] =(byte) 'd';
myArray[3] =(byte) 'e';
myArray[4] =(byte) '1';
}
}
我想知道在Program-1的最后一行中的 MyArray
和在Program-2的最后一行中的 MyArray
之间是否有区别?(有任何区别!)
I want to know if is there any difference between MyArray
in the last line of Program-1 and MyArray
in the last line of Program-2? (Any difference!)
推荐答案
在第二个程序中, {...}
不是数组定界符,它们是块定界符.在这种情况下,它们用于提供所谓的初始化块,该初始化块在实例化您的类的新实例时执行.
In your second program, the { ... }
are not array delimiters, they are block delimetes; in this case they are used to give a so-called initializer block, which is executed when a new instance of your class is instantiated.
创建初始化数组的正确"方法是:
The "correct" way to create an initialized array is:
new byte[] { 1, 2, 3 };
在初始化引用,使用现有引用或将数组传递给方法时,都可以始终使用它:
This can be used always, both when the reference is initialized and when an existing reference is used or when the array is passed to a method:
byte[] myArray = new byte[] { 1, 2, 3 }; // OK
myArray = new byte[] { 4, 5, 6 }; // OK
anObject.someMethod(new byte[] { 7, 8, 9}); // OK
但是,第一种变体非常普遍,因此Java允许您在特定情况下将 new byte []
部分保留为
However, the first variant is very common and therefore Java allows you to leave the new byte[]
part out in that particular case:
byte[] myArray = { 1, 2, 3 }; // OK
myArray = { 4, 5, 6 }; // Does not compile
anObject.someMethod({ 7, 8, 9}); // Does not compile
这篇关于使用和不使用`New`关键字定义数组之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!