我試圖使用從一個文本文件中的信息存儲到一個數組,但該項目要求我們通過進行臨時數組,並提高其大小當我們讀更多的文件器。---新的對象這樣做。我怎樣才能做到這一點?如何製作一個更大的數組並複製java中前一個數組的信息?
/**
* reads a csv data file and returns an array of acquaintances
* @param path File path of CSV file
* @return Acquaintances from the file
*/
public static Acquaintance[] read (String path) {
//create an array of acquaintances
Acquaintance[] acqs = new Acquaintance[0];
//open the file
try {
BufferedReader file = new BufferedReader(new FileReader(path));
//read the file until the end
String line;
while((line = file.readLine()) != null) {
// parse the line just read
String[] parts = line.split(",");
//create an acquaintance object
Acquaintance a = new Acquaintance(parts[0], parts[1], Double.parseDouble(parts[2]));
acqs[0] = a;
//Add the object to the array
//(1) create a new Acquaintance array, with one extra element
Acquaintance[] tmp = new Acquaintance[acqs.length+1];
//(2) copy all old elements into new
Acquaintance[] tmp = acqs.clone();
//(3) assign new Acquaintance object to last element of the array
//(4) assign new array's address to acqs
//for loop
}
這似乎可能是作業? –
檢查'ArrayList'的'ensureCapaciy'方法:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#ArrayList。 ensureCapacity%28int%29 –
不要在有人給出答案後刪除問題。這使其他人無用。 –