public ArrayList FileList() {
ArrayList fileList = new ArrayList(1000000);
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null) {
fileList.add(new String(line));
line = br.readLine();
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileList;
}
为什么我必须要把ArrayList fileList = new ArrayList(1000000)声明成这样才能运行,有没有更好的声明办法.
ArrayList fileList = new ArrayList(1000000);
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null) {
fileList.add(new String(line));
line = br.readLine();
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileList;
}
为什么我必须要把ArrayList fileList = new ArrayList(1000000)声明成这样才能运行,有没有更好的声明办法.
为什么必须要用1000000?说说你的理由。还有提醒一下,add(new String(line))这种用法不好,直接add(line)。
我先前是不想那麻烦,其实我多读一次io流统计一下文本的行数就不用声明一个这大的arraylist啦,现在我想通了,后面行数也是有用的,就写一个统计行数的类算了.其实,我在这里声明这大的一个arraylist,主要是该arraylist有可能会是一个数十万条记录的数组,而在读文件之前程序并不知道该数组会是多大.所以我干脆就声明一个 一百万 的数组.
如果像你这样用ArrayList,那与用普通数组有什么区别?
使用对象当然要先创建了,ArrayList长度是可以根据需要自动增长的,你这个就设置了初始容量,如果你事先知道了大概容量,这么作可以提高效率,毕竟重新分配长度也是需要时间的。
public ArrayList FileList() {
ArrayList fileList = new ArrayList();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null) {
fileList.add(new String(line)); //程序在这段代码处报错
line = br.readLine();
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileList;
}
ArrayList list = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
while((line = br.readLine()) != null)
list.add(line);
br.close();
return list;
}