2017-08-04 17 views
1

を再作成することなく、他のクラスでそれを使用してこれは、メインメソッドで私の配列です:JAVA - mainメソッドで配列リストを作成し、それを

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

私のアプリケーションは、複数のスレッドを持っており、私はこれを使用しようとしています毎回配列を再作成せずにすべてのスレッドで配列(これは巨大です)を作成します。 主な考え方は、何らかの方法でロードされ、他のクラスから呼び出される準備ができていることです。

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?) 
    } 

+2

クラスメンバーに割り当てて、パブリックゲッターを作成するだけです。次に、どこからでも配列を使用できます。私たちがスレッドを話しているなら、それを同期させたいかもしれません。 – SHG

+0

あなたはあなたの質問を精緻化できますか? 1つのことArrayListはスレッドセーフではなく、複数のスレッドがアクセスしているときには使用しないでください。 –

+0

同期されたシングルトンオブジェクトを使用してこのarraylistにアクセスするとどうなりますか –

答えて

0

は、以下のSHGの提案に続いて、あなたにいくつかのアイデア

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

} 
0

を与えるかもしれませ静的と非静的なフィールドの比較はOracle documentationです(基本的には01が必要ですインスタンスはmyarrayにアクセスしますが、あなたはJVM内で別のリストを持つことができます。

関連する問題