(家庭作业:)在这种情况下我想使用数组而不是数组列表。我有数组列表名称 Employee,我必须将其数据插入到树中。我从文件中逐行加载数据。但我想对员工使用数组而不是数组列表。我怎样才能做到这一点 ?在这种情况下,有多种方法可以使用数组而不是数组列表。以下代码是我的 arraylist Employee 的示例代码。我想将 List 更改为 Employee[] 如何以数组的方式编写以下函数。
public static void main(String[] args) {
List<Employee> employees = read("employees.txt");
BST bst = new BST();
for(Employee e : employees){
bst.insert(e);
}
}
public static List<Employee> read(String file) {
try {
List<Employee> employees = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null ){
String[] arr = line.split("-");
Employee emp = new Employee();
emp.ccode = Integer.parseInt(arr[0]);
emp.cus_name = arr[1];
emp.phone = arr[2];
employees.add(emp);
}
return employees;
} catch (IOException ex) {
Logger.getLogger(TestMusic.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
最佳答案
这种方法不是最好的方法,但可能会解决您的问题。用于 java 版本 < 8。 方法是解析文件得到 no。行,创建员工数组,并再次解析以获取所有员工的数据
public static void main(String[] args) {
int empSize = getNumberOfEmployees("employees.txt");
employees = new Employee[empSize];
employees = read("employees.txt");
BST bst = new BST();
for(Employee e : employees){
bst.insert(e);
}
}
public static int getNumberOfEmployees (String file) {
int totalEmp = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null ) {
totalEmp ++;
}
}catch (IOException e) {
e.printStackTrace();
}
return totalEmp;
}
public static Employee[] read(String file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
int i=0;
while((line = reader.readLine()) != null ){
String[] arr = line.split("-");
Employee emp = new Employee();
emp.ccode = Integer.parseInt(arr[0]);
emp.cus_name = arr[1];
emp.phone = arr[2];
employees[i] = emp;
i++;
}
return employees;
} catch (IOException ex) {
Logger.getLogger(TestMusic.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
关于java - 如何使用数组而不是数组列表从java中的文件中逐行加载对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032523/