gpt4 book ai didi

java - 从另一个类向 ArrayList 添加元素

转载 作者:太空宇宙 更新时间:2023-11-04 12:42:09 26 4
gpt4 key购买 nike

我只有这个基本代码,我需要帮助将员工数据添加到另一个类的 ArrayList 中。我只是为了准备作业而编写这段代码,所以不要过多地批评我的代码。但本质上,我需要添加员工元素并最终删除它们。但现在,我只需要帮助将元素添加到我的其他 Employee 类中。 =]

public class main {
private static Employee employee;

public static void main(String[] args) {
employee = new Employee(10,10);
System.out.println(employee.toString());
}
}

............

import java.util.ArrayList;

public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> Employee = new ArrayList<>();

public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}

public String toString(){
return ""+employeeNum+hourRate;
}
}

最佳答案

简单示例 -

package com;

import java.util.ArrayList;

public class TestPage{

public static void main(String[] args){
Employee emp1, emp2;

emp1 = new Employee();
emp2 = new Employee();

emp1.setName("MAK");
emp2.setName("MICHELE");

emp1.setAddress("NY");
emp2.setAddress("WY");

//and keep putting other information like this

ArrayList<Employee> employee = new ArrayList<Employee>();
employee.add(emp1);
employee.add(emp2);

System.out.println("emp1 name is : " + employee.get(0).getName());
System.out.println("emp2 name is : " + employee.get(1).getName());

System.out.println("emp1 address is : " + employee.get(0).getAddress());
System.out.println("emp2 address is : " + employee.get(1).getAddress());
}
}

class Employee{
String name, address;
int age, salary;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}

关于java - 从另一个类向 ArrayList 添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36731901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com