所以这是我在Main方法中的数组:
ArrayList<String> myarray = new ArrayList<>();
while(scan.hasNextLine()){
myarray.add(scan.nextLine());
}
scan.close();
我的应用程序有多个线程,我试图在每个线程中使用这个数组(有点大),而不是每次都重新创建数组。 主要的想法是以某种方式加载它并准备好被其他类调用。
答案 0 :(得分:0)
可能是下面给你一些想法
class Myclass{
private ArrayList<String> myarray = new ArrayList<>();
main(){
//populate the array
}
public ArrayList<String> getList(){
return myarray;
}
}
答案 1 :(得分:0)
遵循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 documentation(基本上,您将需要或不需要MyClass
个实例来获取myarray
访问权限,但您将或者不会,在JVM中可以有不同的列表。)