Java 如何全局声明一个字符串数组。谁能给我一个简单的例子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18722334/
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 to declare a String array globally.could anyone give me a simple example of it
提问by sam
i want to declare an String 1 dimensional array globally. could any one tell me how it can be performed with the help of simple example.
我想全局声明一个字符串一维数组。谁能告诉我如何在简单示例的帮助下执行它。
回答by Juned Ahsan
public static String[] myBadGlobalArray = new String[mybadarrysize];
回答by StormeHawke
...generally speaking global variables are a BADthing. That said, you can declare it as public static String[] someArrayName;
......一般而言全局变量是一个坏事情。也就是说,您可以将其声明为public static String[] someArrayName;
回答by Rahul Tripathi
You can try this:=
你可以试试这个:=
public static String[] myArray = new String[10];
回答by blackpanther
Within a class, a globally defined array could be as follows:
在一个类中,一个全局定义的数组可能如下:
public class MyClass {
public static String[] myArray = new String[yourSize];
}
However, in order to adhere to the concept of encapsulation, please use getters and setters to the array to make it accessible. It can be really easy to be lazy and declare the String[]
as protected
or public
, but don't as this globalisation of variables counteracts/goes against a very important OOP principle of encapsulation.
但是,为了坚持封装的概念,请对数组使用 getter 和 setter,使其可访问。偷懒并声明String[]
as protected
or真的很容易public
,但不要这样做,因为这种变量全球化抵消/违背了非常重要的 OOP 封装原则。
回答by Flinbor
use global public fields only if it can be final another way use something like:
仅当它可以是最终的另一种方式使用全局公共字段时才使用:
private String[] stringArray;
public String[] getStringArray() {
return stringArray;
}
public void setStringArray(String[] stringArray) {
this.stringArray = stringArray;
}