2016-11-21 65 views
0

我想通過傳遞一個參數來創建和更新ArrayList,這樣我就可以得到一個說10個名字的列表;然而,目前的功能似乎並沒有工作 - 任何想法,請問?通過在Java中傳遞參數來更新ArrayList

public String addClient(String name) { 
    ArrayList<String> myList = new ArrayList<String>(); 
    myList.add(name); 

    return myList; 
    } 
+0

'公共字符串了addClient(字符串名稱)'必須返回一個'String',而不是'名單<>'。 – bradimus

+0

你有一個返回類型爲'String'的方法,你正在返回'ArrayList'? –

回答

3

您每次撥打電話時都會創建一個new ArrayList。這意味着每次您調用此方法時,都會創建一個全新的Collection,並只存儲其中的一個客戶端。你需要保留一個單一的集合參考,並繼續增加。你可以通過傳遞數組中要添加到:

public List<String> addClient(String name, List<String> array) { 
    array.add(name); 
    return array; 
} 

這似乎是一個有用的功能沒有,所以我猜這是一個類中。因此,這可能是你想要的方式:

/** 
* Class is not Thread Safe 
*/ 
public class ClientList { 
    private final ArrayList<string> clients; 

    public ClientList() { 
     this.clients = new ArrayList<>(); 
    } 

    public void addClient(String client) { 
     this.clients.add(client); 
    } 

    public List<String> getClients() { 
     // Note: Never give a reference to the internal objects of the class 
     // as that means someone outside this class can own a reference to it 
     // and can update the object without you knowing (by not going 
     // through this class) 
     Collections.unmodifiableList(this.clients); 
    } 
} 
+0

並返回列表

+1

已更新。雖然這看起來像一個非常奇怪的方法 - 除非你正在做一個Builder模式... – justderb

+0

'ClientList'類看起來像一個有效的解決方案給我,但如果我們走得更遠,並希望使它成爲一個線程安全的,那麼我們會必須以不同的方式進行升技。 :) –

0

這是你需要做什麼:

ArrayList<String> myList = new ArrayList<String>(); 

public void addClient(String name) { 
    myList.add(name); 
} 

如果創建的方法中的列表,它只會有一個值,而會去一旦方法執行完成(除非它返回)。看看不同的範圍here。您應該在課程級別創建一個列表並將其添加到其中。

此外,方法不需要返回任何東西,因此最好將類型更改爲void

0

您的方法存在的問題是,每次調用方法addClient時,都會創建一個新的ArrayList。 我認爲這會爲你工作:

static ArrayList<String> myList; 

public static void main(String[] args) { 
    myList = new ArrayList<>(); 
} 

public void addClient(String name){ 
    myList.add(name);    
}