I am working on an assignment in which I have to:
Create an Employee class with the following attributes/variables: name age department
Create a class called Department which will contain a list of employees.
a. Department class will have a method which will return its employees ordered by age.
b. Value of Department can be only one of the following:
I am having the hardest time trying to figure out how to complete 2b. Here is what I have so far:
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());
}
});
}
}
You can use enumerations for the same purpose which will restrict you to use only specified values.
Declare your Department
enum as follows
public enum Department {
Accounting, Marketting, Human_Resources, Information_Systems
}
You Employee
class can now be
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;
}
}
and while creating employee, you can use
Employee employee = new Employee("Prasad", 47, Department.Information_Systems);
EDIT as suggested by Adrian Shum and of course because it is a great suggestion.
We wil modify enum to include toString()
method and constructor
which takes a string argument.
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;
}
}
So when we are creating an Employee
object as follows and using it,
Employee employee = new Employee("Prasad Kharkar", 47, Department.INFORMATION_SYSTEMS);
System.out.println(employee.getDepartment());
We will get a readable string representation as Information Systems
as it is returned by toString()
method which is called implicitly by System.out.println()
statement.
Read the good tutorial about Enumerations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With