2017-08-04 21 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中擁有不同的列表)。

相關問題