簡體   English   中英

為什么我無法通過其他方法顯示我的列表?

[英]Why I can't show my list from another method?

你能告訴我為什么當我嘗試從其他方法啟動它時看不到我的列表嗎? 以下方法:

public class CollectionsOperation {
    private  List<Client> bufferedReaderClientLIst = new ArrayList<Client>();
    private  List<Client> emptyBoxForCf = new ArrayList<Client>();
    BufferedReader bf = null;


    private static final String fileName = "Clients.txt";

    public List<Client> bufferedReaderCollection() throws IOException {
        String line;        

        bf = new BufferedReader(new InputStreamReader (new FileInputStream(fileName), "UTF-8"));

        while((line = bf.readLine()) != null) {

               String[] split = line.split(";"); 
               String nameCompany = split[0].substring(2);
               String adress = split[1]; 
               String phoneNumber = split[2]; 
               String emailAdress = split[3];

               Client k = new Client(nameCompany, adress, phoneNumber, emailAdress);
               bufferedReaderClientLIst.add(k); 
        }
        System.out.println(bufferedReaderClientLIst); 

        return bufferedReaderClientLIst;

    }
    public void show() throws IOException {
        CollectionsOperation k = new CollectionsOperation();
        k.bufferedReaderCollection();
        System.out.println(bufferedReaderClientLIst); 
    }

調用方法:

public static void main(String[] args) throws IOException { 
        CollectionsOperation k = new CollectionsOperation();                
        k.show();
}

這就是我得到的結果:

[ MarkCompany';Ilusiana';0982882902';mark@company.com,  CorporationX';Berlin';93983';X@Corporation.com]
[]

為什么第二個列表是空的? 方法bufferedReaderCollection()返回一個結果,並且列表bufferedReaderClientLIst可用於所有方法。 怎么了?

show()

public void show() throws IOException {
    CollectionsOperation k = new CollectionsOperation();
    k.bufferedReaderCollection();
    System.out.println(bufferedReaderClientLIst); 
}

您創建另一個CollectionsOperation對象來調用bufferedReaderCollection() 這是不必要的。

但是,問題出在您打印bufferedReaderClientList的最后一個打印語句中。 這是打印this實例的bufferedReaderClientList ,而不是k 因為您沒有在this上調用bufferedReaderCollection ,所以列表將為空,因此[]打印在最后。

而不是創建另一個實例,使用this

public void show() throws IOException {
    this.bufferedReaderCollection();
    System.out.println(bufferedReaderClientLIst); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM