我正在完成一项任务,我必须:
使用以下属性/变量创建Employee类:name age department
创建一个名为Department的类,它将包含一个雇员列表.
一个.部门类将有一种方法,将按年龄命令退还其员工.
湾 部门的价值只能是以下之一:
我正在努力想弄清楚如何完成2b.这是我到目前为止:
import java.util.*;
public class Employee {
String name;
int age;
String department;
Employee (String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
int getAge() {
return age;
}
}
class Department {
public static void main(String[] args) {
List<Employee>empList = new ArrayList<Employee>();
Collections.sort (empList, new Comparator<Employee>() {
public int compare (Employee e1, Employee e2) {
return new Integer (e1.getAge()).compareTo(e2.getAge());
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*kar 15
您可以将枚举用于相同的目的,这将限制您仅使用指定的值.Department
按如下方式声明您的枚举
public enum Department {
Accounting, Marketting, Human_Resources, Information_Systems
}
Run Code Online (Sandbox Code Playgroud)
你Employee
现在可以上课了
public class Employee {
String name;
int age;
Department department;
Employee(String name, int age, Department department) {
this.name = name;
this.age = age;
this.department = department;
}
int getAge() {
return age;
}
}
Run Code Online (Sandbox Code Playgroud)
在创建员工时,您可以使用
Employee employee = new Employee("Prasad", 47, Department.Information_Systems);
Run Code Online (Sandbox Code Playgroud)
按照Adrian Shum的建议进行编辑,当然因为这是一个很好的建议.
我们将修改枚举以包含toString()
方法,constructor
并采用字符串参数.
public enum Department {
ACCOUNTING("Accounting"), MARKETTING("Marketting"), HUMAN_RESOURCES(
"Human Resources"), INFORMATION_SYSTEMS("Information Systems");
private String deptName;
Department(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return this.deptName;
}
}
Run Code Online (Sandbox Code Playgroud)因此,当我们Employee
按如下方式创建对象并使用它时,
Employee employee = new Employee("Prasad Kharkar", 47, Department.INFORMATION_SYSTEMS);
System.out.println(employee.getDepartment());
Run Code Online (Sandbox Code Playgroud)
我们将得到一个可读的字符串表示形式,Information Systems
因为它是toString()
由System.out.println()
语句隐式调用的方法返回的.阅读关于Enumerations的好教程
归档时间: |
|
查看次数: |
5256 次 |
最近记录: |