2017-08-04 25 views
1

所以这是我的数组中的主要方法:JAVA - 创造主要方法数组列表和其他类中使用它无需重新创建它

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

我的应用程序有多个线程,我试图用这个数组(每个线程都有一个巨大的数组),而不是每次重新创建数组。 主要思想是以某种方式加载并准备好由其他类调用。

+2

只需将其分配给一个类成员,并为其创建一个公共getter。然后你可以在任何地方使用这个数组。如果我们正在讨论话题,你可能想同步它。 – SHG

+0

你能否详细说明你的问题。有一件事ArrayList不是线程安全的,不应该在多线程访问它时使用。 –

+0

如何使用同步的单例对象访问此数组列表 –

回答

0

可能低于给你一些想法

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

} 
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中拥有不同的列表)。

相关问题