【问题标题】:Why I can't show my list from another method?为什么我不能通过其他方法显示我的列表?
【发布时间】:2020-04-07 19:46:24
【问题描述】:

你能告诉我为什么当我尝试从另一种方法启动时我看不到我的列表吗?以下方法:

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() 创建另一个CollectionsOperation 对象?

标签: java arrays list methods return


【解决方案1】:

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

【讨论】:

  • 现在可以了。谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-22
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 2017-04-22
  • 1970-01-01
相关资源
最近更新 更多