JAVA - 在main方法中创建数组列表并在其他类中使用它而不重新创建它



所以这是我在 Main 方法中的数组:

ArrayList<String> myarray = new ArrayList<>();
while(scan.hasNextLine()){
myarray.add(scan.nextLine());
}
scan.close();

我的应用程序有多个线程,我正在尝试在每个线程中使用此数组(这有点大(,而无需每次都重新创建数组。 主要思想是以某种方式加载它并准备好被其他类调用。

可能下面给你一些想法

class Myclass{
private ArrayList<String> myarray = new ArrayList<>();
main(){
//populate the array
} 
public ArrayList<String> getList(){
return myarray;
}
}

以下 SHG 建议:

public MyStaticClass {
// from your question is not clear whether you need a static or non static List
// I will assume a static variable is ok
// the right-hand member should be enough to synchornize your ArrayList
public static List<String> myarray = Collections.synchronizedList(new ArrayList<String>());
public static void main(String[] args) {
// your stuff (which contains scanner initialization?)
ArrayList<String> myarray = new ArrayList<>();
while(scan.hasNextLine()){
myarray.add(scan.nextLine());
}
scan.close();
// your stuff (which contains thread initialization?)
}

但是如果你真的需要一个非静态变量

public MyClass {
private final List<String> myarray;
public MyClass() {
// the right-hand member should be enough to synchornize your ArrayList
myarray = Collections.synchronizedList(new ArrayList<String>());
}
public void getArray() {
return myarray;
}

public static void main(String[] args) {
// your stuff (which contains scanner initialization?)
Myclass myObj = new MyClass();
List<String> myObjArray = myObj.getArray();
while(scan.hasNextLine()){
myObjArray.add(scan.nextLine());
}
scan.close();
// your stuff (which contains thread initialization?)
}

有关静态字段与非静态字段的详细信息,请查看 Oracle 文档(基本上,您将或不需要MyClass实例来获取myarray访问权限,但您将或不会能够在 JVM 中拥有不同的列表(。