用java 1.定义一个员工:employee 类,包含 姓名,年龄,薪资,地址等属性。 2. 创建5个员工对象,放入集合中。 如果 薪资大于 2000元的放在 arrayList1中 如果薪资大于5000元放入arrayList2中
时间: 2024-04-09 14:28:40 浏览: 165
好的,下面是使用Java定义员工类以及创建员工对象并放入集合的示例代码:
```java
import java.util.ArrayList;
public class Employee {
private String name;
private int age;
private double salary;
private String address;
public Employee(String name, int age, double salary, String address) {
this.name = name;
this.age = age;
this.salary = salary;
this.address = address;
}
public static void main(String[] args) {
ArrayList<Employee> arrayList1 = new ArrayList<>();
ArrayList<Employee> arrayList2 = new ArrayList<>();
Employee emp1 = new Employee("John", 30, 2500, "123 Main St");
Employee emp2 = new Employee("Alice", 35, 3000, "456 Elm St");
Employee emp3 = new Employee("Bob", 28, 4000, "789 Oak St");
Employee emp4 = new Employee("Emily", 40, 6000, "999 Pine St");
Employee emp5 = new Employee("Mike", 32, 1800, "222 Maple St");
ArrayList<Employee> employees = new ArrayList<>();
employees.add(emp1);
employees.add(emp2);
employees.add(emp3);
employees.add(emp4);
employees.add(emp5);
for (Employee emp : employees) {
if (emp.getSalary() > 2000) {
arrayList1.add(emp);
}
if (emp.getSalary() > 5000) {
arrayList2.add(emp);
}
}
System.out.println("ArrayList1:");
for (Employee emp : arrayList1) {
System.out.println(emp.getName());
}
System.out.println("ArrayList2:");
for (Employee emp : arrayList2) {
System.out.println(emp.getName());
}
}
// Getters and Setters
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public String getAddress() {
return address;
}
}
```
在上面的代码中,我们定义了一个名为`Employee`的类,包含了姓名(name),年龄(age),薪资(salary),地址(address)等属性。然后,我们创建了5个员工对象,并将它们放入一个名为`employees`的ArrayList集合中。
接下来,我们遍历`employees`集合,根据薪资的条件,将员工对象分别放入`arrayList1`和`arrayList2`这两个ArrayList集合中。
最后,我们分别打印输出`arrayList1`和`arrayList2`中的员工姓名。
请注意,为了使属性能够被访问到,我们还提供了相应的getter方法。
阅读全文