java 如何定义全局数组并在Java中调用不同的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25687833/
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 define Global Array and call in different classes in Java
提问by Newbie
I am working on an assignment in Java and having a 2D array. I have created multiple classes and at the moment I am creating the array in each and every class and was wondering if there is an easy way to create the array only once in the whole program and call it in different classes. I have created a 2D array and I don't want to use ARRAYLIST (as per my knowledge ARRAYLIST is used when there is no fixed size of array but in my case I know my ARRAY is 5x5).
我正在用 Java 完成一项任务并有一个二维数组。我创建了多个类,目前我正在每个类中创建数组,并且想知道是否有一种简单的方法可以在整个程序中只创建一次数组并在不同的类中调用它。我创建了一个二维数组,我不想使用 ARRAYLIST(据我所知,当没有固定大小的数组时使用 ARRAYLIST,但在我的情况下,我知道我的 ARRAY 是 5x5)。
Here is a basic example of my code:
这是我的代码的基本示例:
public class accounts{
static int option=0;
static String[][] resultCard = new String[][]{
{ "", "A", "B", "C", "D", "E"},
{ "Account1", "1", "2","3","4","5" },
{ "Account2", "6", "7", "8", "9", "10"},
{ "Account3", "11", "12", "13", "14", "15"},
{ "Account4", "16", "17", "18", "19", "20"},
{ "Account5", "21", "22", "23", "24", "25"}
};
public static void method1() {
//I have entered some code here
}
}
Then I have created another class as follows:
然后我创建了另一个类,如下所示:
public class customers{
static int option=0;
static String[][] resultCard = new String[][]{
{ "", "A", "B", "C", "D", "E"},
{ "Account1", "1", "2","3","4","5" },
{ "Account2", "6", "7", "8", "9", "10"},
{ "Account3", "11", "12", "13", "14", "15"},
{ "Account4", "16", "17", "18", "19", "20"},
{ "Account5", "21", "22", "23", "24", "25"}
};
public static void method2() {
//I have entered some code here
}
I have another class as follows:
我还有一个课程如下:
public class staff{
static int option=0;
static String[][] resultCard = new String[][]{
{ "", "A", "B", "C", "D", "E"},
{ "Account1", "1", "2","3","4","5" },
{ "Account2", "6", "7", "8", "9", "10"},
{ "Account3", "11", "12", "13", "14", "15"},
{ "Account4", "16", "17", "18", "19", "20"},
{ "Account5", "21", "22", "23", "24", "25"}
};
public static void method1() {
//I have entered some code here
}
public static void method1() {
//I have entered some code here
}
I want to know that instead of creating the array in each class, is it possible that I create one global array in only 01 class and call the array in different classes.
我想知道,不是在每个类中创建数组,我是否可以只在 01 类中创建一个全局数组并在不同的类中调用该数组。
回答by Dan Pantry
Whilst the other answers will work fine for your needs, you should neveruse public static
on a mutable (changeable) field - this means that anyone can change the field anywhere in your application and cause unknown behaviour. Primitives (int double float
) won't change if you add final
modifier, but an Object like an array can have it's contents modified - only the object reference itself will be constant. As a result - the array is mutable, so you shouldn't use public static
on it.
虽然其他的答案将正常工作的需要,您应该永远使用public static
,这意味着任何人都可以改变你的应用领域的任何地方和原因不明的行为-一个可变的(可更换)场。int double float
如果添加final
修饰符,基元 ( ) 不会改变 ,但是像数组这样的对象可以修改其内容 - 只有对象引用本身是常量。结果 - 数组是可变的,所以你不应该使用public static
它。
It appears that your String[][]
is almost meant to represent a table, with the first element in the String[][]
being a header, and each other row being a new row in this table. As a result of this, we can turn your String[][]
into something more idiomatic.
看起来您String[][]
几乎意味着代表一个表格,其中的第一个元素String[][]
是标题,而每一行都是该表格中的一个新行。因此,我们可以将您的内容String[][]
变成更地道的东西。
We can make each row of your String[][]
be represented by an instance of a class. There are a few benefits of this, but namely it means that you can look at it and say "this is X", rather than "this is an array of strings".
我们可以让你的每一行都String[][]
用一个类的实例来表示。这样做有一些好处,但这意味着您可以查看它并说“这是 X”,而不是“这是一个字符串数组”。
public class Account {
private final String name;
private final String a, b, c, d, e;
public Account(String name, String a, String b, String c, String d, String e) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.name = name;
}
public string getName() { return this.name; }
public string getA() { return this.a; }
public string getB() { return this.b; }
public string getC() { return this.c; }
public string getD() { return this.d; }
public string getE() { return this.e; }
}
This encapsulatesthose fields inside of an object. This is great because it means that first of all, you have control over where your fields are assigned and where they can be changed as well.
这将这些字段封装在一个对象中。这很好,因为这意味着首先,您可以控制字段的分配位置以及可以更改的位置。
Now, we can turn your String[][]
into an Account[]
. As mentioned above, sharing an array directly is bad practise. How do we get around this? Well, we can create another class that controls the lifetime of these accounts. Since it is a data store, let's call it a repository (NB: This is known as the repository pattern).
现在,我们可以将您String[][]
的Account[]
. 如上所述,直接共享数组是不好的做法。我们如何解决这个问题?好吧,我们可以创建另一个类来控制这些帐户的生命周期。由于它是一个数据存储,我们称其为存储库(注意:这称为存储库模式)。
public class AccountRepository {
private final Collection<Account> accounts;
public AccountRepository(Collection<Account> accounts) {
this.accounts = accounts;
}
public Account getByName(String accountName) {
// Note that this is very inefficient, and I would not recommend using it in real code
for(Account account : this.accounts) {
if(account.getName().equalsIgnoreCase(accountName)) {
return account;
}
}
// Note: Returning null vs throwing exception is out of scope of this example.
return null;
}
public Iterator<Account> getAccounts() {
return this.accounts.getIterator();
}
}
Now this gives us a data store that could potentially be used to store any number of Account
s and from, potentially, any source - we don't need to worry about passing around arrays because we can pass an instance of this around, andthe best bit is that we give interested parties an Iterator<Account>
and not an Account[]
. The reason this is great is because Iterators
are immutable - you cannot change them. Seeing this, now, we can create your other two classes (Staff, and Customers - whose names and purposes are another subject for debate outside of this question) and tell them that they don't need to worry about an String[][]
- they can just take an instance of AccountRepository
in their constructor.
现在,这为我们提供了一个数据存储,它可能用于存储任意数量的Account
s 并且可能来自任何来源 - 我们不需要担心传递数组,因为我们可以传递 this 的一个实例,并且最好位是我们给感兴趣的各方一个Iterator<Account>
而不是一个Account[]
。这很棒的原因是因为Iterators
它们是不可变的——你不能改变它们。看到这一点,现在,我们可以创建你的另外两个类(员工和客户——他们的名字和目的是这个问题之外的另一个辩论主题)并告诉他们他们不需要担心String[][]
——他们可以AccountRepository
在他们的构造函数中的一个实例。
public class Customers {
private final AccountRepository accountRepository;
public Customers(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public void method1() {
// do something
}
}
public class Staff {
private final AccountRepository accountRepository;
public Staff(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public void method1() {
// do something
}
}
This makes your code a lotmore flexible and maintainable andeasy to follow. Your Staff
and Customers
instances would require an AccountRepository
to be created, which could be the same one, and those classes would call the methods on the AccountRepository
to access the data safely without opportunity for it being changed.
这使你的代码很多更灵活,更易于维护,并易于遵循。您的Staff
和Customers
实例需要AccountRepository
创建一个,这可能是同一个,并且这些类将调用 上的方法AccountRepository
来安全地访问数据,而没有机会对其进行更改。
Account[] accounts = new Account[] {
new Account("Account1", "1", "2", "3", "4", "5"),
// the rest of the accounts
};
AccountRepository repository = new AccountRepository(Arrays.asList(accounts));
Customers customers = new Customers(repository);
Staff staff = new Staff(repository);
In my opinion you should always try to avoid "static" properties or fields - the usage of which indicates a code smell the majority of the time.
在我看来,您应该始终尽量避免“静态”属性或字段 -大多数情况下使用它们表明代码有异味。
Hope this helps and doesn't confuse you.
希望这对您有所帮助并且不会让您感到困惑。
回答by sidgate
You can have a public class that defines the static variable as public. Then in other classes you can access it with className.variableName
or use static import
您可以拥有一个将静态变量定义为公共的公共类。然后在其他类中,您可以访问它className.variableName
或使用static import
public class GlobalVariables {
public static final String[][] resultCard = new String[][]{
{ "", "A", "B", "C", "D", "E"},
{ "Account1", "1", "2","3","4","5" },
{ "Account2", "6", "7", "8", "9", "10"},
{ "Account3", "11", "12", "13", "14", "15"},
{ "Account4", "16", "17", "18", "19", "20"},
{ "Account5", "21", "22", "23", "24", "25"}
};
}
And the acccounts.java would look like this
acccounts.java 看起来像这样
import static GlobalVariables.*;
public class accounts{
public void someMethod(){
resultCard[0]. ....
}
}
In case the variable is constant, you can mark it final.
如果变量是常量,您可以将其标记为 final。
回答by Kevin Cruijssen
It looks like your array is constant and won't change. When I have constants like this that I use in multiple classes I create a Defaults.java file. In this Defaults-file I can add, pretty obvious, the defaults of the app. In your case it would be something like this:
看起来您的数组是恒定的并且不会改变。当我在多个类中使用这样的常量时,我创建了一个 Defaults.java 文件。在这个默认文件中,我可以很明显地添加应用程序的默认值。在你的情况下,它会是这样的:
public class Defaults
{
public static final String[][] resultCard = new String[][]{
{ "", "A", "B", "C", "D", "E"},
{ "Account1", "1", "2","3","4","5" },
{ "Account2", "6", "7", "8", "9", "10"},
{ "Account3", "11", "12", "13", "14", "15"},
{ "Account4", "16", "17", "18", "19", "20"},
{ "Account5", "21", "22", "23", "24", "25"}
};
}
You can then use this array in your other classes like so:
然后,您可以在其他类中使用此数组,如下所示:
public class customers
{
private static int option = 0;
public static void method2() {
// I have entered some code here
// You can use the resultCard like so:
// Defaults.resultCard
// As an example: Get the "B" in the array:
String result = Defaults.resultCard[0][2];
}
}
If you don't want to have a final array, since you want to add, edit or delete from the array I would suggest creating a seperated Model-class for this array, with a Getter and Setter (and perhaps an Add-, Edit- and/or Remove-method).
如果您不想拥有最终数组,因为您想从数组中添加、编辑或删除,我建议为此数组创建一个单独的模型类,使用 Getter 和 Setter(可能还有一个 Add-、Edit - 和/或删除方法)。
Fields that are used in this Defaults-file shouldn't be changed and should be public static final
.
此默认文件中使用的字段不应更改,而应为public static final
.