2017-04-09 50 views
3

對於我正在做的項目,我想使用單獨的類來將各種人的信息存儲在數組列表中。在這種情況下,該方法將包含字符串的ArrayList以存儲我的所有信息。當我嘗試這樣做時,我意識到每當我運行storage向arraylist添加一個字符串時,它就會擺脫arraylist中的所有以前的信息。如何在java中使用方法存儲來自數組列表的信息


是有可能使它所以兩個字符串Hello, How Are You?I'm fine. How Are You?添加到two類陣列無需一旦該方法被重新運行陣列復位?

​​

給定輸出:

[Hello, How Are You?] [I'm fine. How Are You?]

預期輸出:

[Hello, How Are You?] [Hello, How Are You?, I'm fine. How Are You?]

+0

你需要初始化你的方法之外的數組列表,但你爲什麼即使初始化對象,如果你需要的只是靜態方法 –

+0

提示:閱讀有關Java命名約定。類去UpperCase。除此之外:這是非常基本的東西;可能在*任何有關這個主題的書中解釋。 – GhostCat

回答

2

有解決你的問題兩個選項:

賓得N(1):您當前ArrayList範圍是本地storage方法,因爲你是在每次調用創建一個全新newArrayList(以storage()方法),但你需要的是如下圖所示,在類級別staticArrayList對象,但是因爲你使用一個對象調用storage()方法,所以這不是可取的選擇(清楚地說明如下),並且編譯器已經發出警告並且你忽略了它。

public class two { 

    private static ArrayList<String> al = new ArrayList<String>(); 

    public static void storage(String toBeAdded) 
    { 
     al.add(toBeAdded); 
     System.out.println(al); 
    } 
} 

選項(2)(首選此):刪除static範圍和申報ArrayList<String>作爲如下所示的實例變量(喜歡此選項),因爲使用的是一個對象的引用是調用一個static方法不是必需的,並造成混亂。

public class two { 

     private ArrayList<String> al = new ArrayList<String>(); 

     public void storage(String toBeAdded) 
     { 
      al.add(toBeAdded); 
      System.out.println(al); 
     } 
    } 

始終確保static變量/方法被調用使用類名(如Two.storage()),而不因爲它們是類級別成員即,它們不是用於單個對象創建任何對象。我強烈建議你閱讀this並更清楚地理解這個主題。


除上述重要的一點,始終確保你跟隨像類名的Java 命名標準應該大寫,你違反了開始。

+0

甚至更​​好,從代碼中刪除所有出現的'static'。 – Bohemian

+0

謝謝你,你是對的 – developer

2

不是將ArrayList聲明爲局部變量,而是將其用作字段。也使該方法非靜態

public class two 
{ 

    private ArrayList<String> al = new ArrayList<String>(); 
    public void storage(String toBeAdded) 
    { 

     al.add(toBeAdded); 
     System.out.println(al); 
    } 
} 
1

你的錯誤

每次你調用storage()方法,你正在創建「的ArrayList」的新對象。

解決方案

因此,請two類的對象和方法傳遞非常久遠的字符串的方法storage()

import java.util.ArrayList; 
    public class one 
    { 
     public static void main (String [] args) 
     { 
      two t = new two(); 

      t.storage(t,"Hello, How Are You?"); 
      t.storage(t,"I'm fine. How Are You?"); 
     } 
    } 

    class two 
    { 
     ArrayList<String> al = new ArrayList<String>(); 
     public static void storage(two object,String toBeAdded) 
     { 


      object.al.add(toBeAdded); 
      System.out.println(object.al); 
     } 
    } 
0

two類問題storage你的邏輯ISN」 t每當你調用存儲來保存新字符串時,你都會創建新的陣列列表al,這將刪除舊列陣列表中的所有先前信息。

,以解決兩個類中定義static ArrayList和通過方法存儲將它添加信息:

public class two 
{ 
    public static ArrayList<String> al = new ArrayList<String>(); 

    public void storage(String toBeAdded) 
    { 
     al.add(toBeAdded); 
     System.out.println(al); 
    } 
} 

注意:也storage方法不應該是static方法,因爲你正在創建two類對象並通過此對象調用方法,所以如果您嘗試測試它會給您警告:

訪問靜態方法存儲

警告您嘗試訪問類two的對象t中的靜態方法storage的原因。

在聲明中類的靜態方法,以正確的方式來調用它:

ClassName.MethodName() 

在你的榜樣:

two.storage("Hello, How Are You?"); 
two.storage("I'm fine. How Are You?"); 
相關問題