如何 Return 当前 Class 的实例作为 TreeMap 中的值?
How Do I Return An Instance of the Current Class as a Value within a TreeMap?
我必须 return 我当时所在的 class 的一个实例,作为 TreeMap 中的变量之一,我正在 return 主 class。我似乎无法弄清楚我应该怎么做。这是我的代码,向您展示我的意思:
public class Employee {
public static Map<String,Employee> load() {
String a="";
String b="";
String [] c;
TreeMap<String, Employee> d=new TreeMap<>();
try {
Scanner in=new Scanner(new File("employees.txt"));
while(in.hasNextLine()){
c=in.nextLine().split(" ");
a=c[0];
b=c[1];
}
//Naturally, the "b" below has a red quiggly line under it as this is a string
d.put(a,b);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return d;
}
}
您需要使用 new
实际构造一个 Employee
。类似于:
public class Employee {
private final String name;
public Employee(String name) {
this.name = name;
}
public static Map<String,Employee> load() throws FileNotFoundException {
TreeMap<String, Employee> map = new TreeMap<>();
Scanner in = new Scanner(new File("employees.txt"));
while(in.hasNextLine()) {
String[] input = in.nextLine().split(" ");
map.put(input[0], new Employee(input[1]));
}
return map;
}
}
更好的设计是将加载逻辑放在单独的 class 中。使用一些最近的 Java 功能:
record Employee(String name) { }
public class EmployeeIndex {
private final Map<String,Employee> index;
public EmployeeIndex(String filename) {
this.index = Files.lines(Paths.get(filename))
.map(String::split)
.collect(Collectors.toMap(a -> a[0], a -> new Employee(a[1]));
}
}
我必须 return 我当时所在的 class 的一个实例,作为 TreeMap 中的变量之一,我正在 return 主 class。我似乎无法弄清楚我应该怎么做。这是我的代码,向您展示我的意思:
public class Employee {
public static Map<String,Employee> load() {
String a="";
String b="";
String [] c;
TreeMap<String, Employee> d=new TreeMap<>();
try {
Scanner in=new Scanner(new File("employees.txt"));
while(in.hasNextLine()){
c=in.nextLine().split(" ");
a=c[0];
b=c[1];
}
//Naturally, the "b" below has a red quiggly line under it as this is a string
d.put(a,b);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return d;
}
}
您需要使用 new
实际构造一个 Employee
。类似于:
public class Employee {
private final String name;
public Employee(String name) {
this.name = name;
}
public static Map<String,Employee> load() throws FileNotFoundException {
TreeMap<String, Employee> map = new TreeMap<>();
Scanner in = new Scanner(new File("employees.txt"));
while(in.hasNextLine()) {
String[] input = in.nextLine().split(" ");
map.put(input[0], new Employee(input[1]));
}
return map;
}
}
更好的设计是将加载逻辑放在单独的 class 中。使用一些最近的 Java 功能:
record Employee(String name) { }
public class EmployeeIndex {
private final Map<String,Employee> index;
public EmployeeIndex(String filename) {
this.index = Files.lines(Paths.get(filename))
.map(String::split)
.collect(Collectors.toMap(a -> a[0], a -> new Employee(a[1]));
}
}