您能告诉我为什么尝试使用其他方法启动列表时看不到列表吗?下面的方法:
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
可用于所有方法。怎么了?
答案 0 :(得分:3)
在show()
中:
public void show() throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
您创建另一个CollectionsOperation
对象以调用bufferedReaderCollection()
。这是不必要的。
但是问题出在您打印bufferedReaderClientList
的最后一个打印语句中。这是在打印bufferedReaderClientList
实例的this
,而不是k
。由于您尚未在bufferedReaderCollection
上调用this
,因此该列表将为空,因此[]
将显示在末尾。
使用this
代替创建另一个实例:
public void show() throws IOException {
this.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}