如何在ArrayList中设置对象变量的值

yth*_*son 4 java arraylist

我正在完成一项任务,我必须:

  1. 使用以下属性/变量创建Employee类:name age department

  2. 创建一个名为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的建议进行编辑,当然因为这是一个很好的建议.

  • 枚举是常量,这就是为什么根据java约定以大写字母声明它的好处.
  • 但我们不希望看到枚举的大写表示,因此我们可以创建枚举构造函数并将可读信息传递给它.
  • 我们将修改枚举以包含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的好教程