4

私は次のことをしなければならない課題に取り組んでいます。

  1. 次の属性/変数を持つ Employee クラスを作成します: name age department

  2. 従業員のリストを含む Department というクラスを作成します。

    を。部門クラスには、従業員を年齢順に返すメソッドがあります。

    b. 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());
        }
    });
    }
}   
4

1 に答える 1

15

指定された値のみを使用するように制限する同じ目的で列挙を使用できます。Department次のように列挙型を宣言します

public enum Department {

    Accounting, Marketting, Human_Resources, Information_Systems

}

あなた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;
    }
}

従業員の作成中に、使用できます

Employee employee = new Employee("Prasad", 47, Department.Information_Systems);

Adrian Shumが提案したように編集します。もちろん、それは素晴らしい提案だからです。

  • 列挙型は定数であるため、Java の規則に従って大文字で宣言するのが適切です。
  • しかし、列挙型の大文字表現を見せたくないので、列挙型コンストラクターを作成して読み取り可能な情報をそれに渡します。
  • enum を変更して、文字列引数を取るtoString()method とwhich を含めます。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;
       }
    
    }
    

したがって、Employee次のようにオブジェクトを作成して使用する場合、

Employee employee = new Employee("Prasad Kharkar", 47, Department.INFORMATION_SYSTEMS);
System.out.println(employee.getDepartment()); 

ステートメントによって暗黙的に呼び出されるメソッドInformation Systemsによって返されるので、読み取り可能な文字列表現を取得します。列挙型に関する優れたチュートリアルを読むtoString()System.out.println()

于 2013-07-12T03:23:14.077 に答える