java 如何调用初始化数组长度的数组构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17529249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I call an Array constructor initializing the Array length?
提问by Martin G
How do I make a constructor to set the length of a global array?
如何使构造函数设置全局数组的长度?
I have already tried several ways to do it, none successful.
我已经尝试了几种方法来做到这一点,但都没有成功。
Example:
例子:
public Class{
public Class(int length){
double[] array = new double[length]; <- this is not global
L = length;
}
int L;
double[] array = new double[L]; <- this does not work
}
I need an array with a length determined by Constructor.
我需要一个长度由构造函数确定的数组。
回答by Bohemian
I think it's as simple as this:
我认为就这么简单:
public class MyClass{
double[] array;
public MyClass(int length){
array = new double[length];
}
}
I've also made the code actually compile:) You were missing some keywords etc.
我还让代码实际编译了:) 你错过了一些关键字等。
If you want to access length
in your code, use array.length
rather than storing it redundantly in a separate field.
如果要length
在代码中访问,请使用array.length
而不是将其冗余存储在单独的字段中。
Also calling your class Class
is a bad choice, even as an example, because it clashes with java.lang.Class
.
Class
即使作为一个例子,调用你的类也是一个糟糕的选择,因为它与java.lang.Class
.
回答by mistahenry
public class aClass{
//define the variable name here, but wait to initialize it in the constructor
public double[] array;
public aClass(int length){
array = new double[length];
}
}
回答by stinepike
Declare the array as member variable. Then initialize it in the constructor.
将数组声明为成员变量。然后在构造函数中初始化它。
public class A{
private double[] array;
public Class(int length){
array = new double[length];
L = length;
}
}
You could initialize it in second way. But then you need to use a fixed length
你可以用第二种方式初始化它。但是你需要使用固定长度
public class A{
private double[] array = new double[100]; // use fixed length
public Class(int length){
array = new double[length];
L = length;
}
}
回答by M. Abbas
I don't know what you are trying to achieve but why you don't simply do it this way:
我不知道你想要达到什么目的,但你为什么不简单地这样做:
public class Class{
public Class(int length){
this.array = new double[length]; // <- this is not global
}
double[] array;
}
回答by Suresh Atta
You can do it
你能行的
public class Test {
double[] array;
public Test (int length){
array = new double[length]; <- this is not global
}