gpt4 book ai didi

java - 将对象存储在 arraylist 中并返回这些对象

转载 作者:行者123 更新时间:2023-12-02 08:34:35 25 4
gpt4 key购买 nike

import java.util.*;
import java.util.ArrayList;

class Employee{

int eid;
String eName;
String eAddr;
int eSalary;

public Employee(int eid,String eName,String eAddr,int eSalary){
this.eid = eid;
this.eName = eName;
this.eAddr = eAddr;
this.eSalary=eSalary;
}
}

class EmployeeDB{

ArrayList<Employee> al = new ArrayList<Employee>();

public boolean addEmployee(Employee e){
return al.add(e);
}

public Employee[] listAll() {
Employee[] array = new Employee[al.size()];
System.out.println("SIZE is : "+al.size());
return al.toArray(array);
}
}



public class Main
{
public static void main(String[] args) {
System.out.println(" ");

Employee e1 = new Employee(111,"Employee-1","loc-1",100);
EmployeeDB d1 = new EmployeeDB();
d1.addEmployee(e1);


Employee e2 = new Employee(222,"Employee-2","loc-2",200);
EmployeeDB d2 = new EmployeeDB();
d2.addEmployee(e2);

EmployeeDB x = new EmployeeDB();
Employee[] arr = x.listAll();

for(Employee e : arr){
System.out.println( e.eid );
System.out.println( e.eName );
System.out.println( e.eAddr );
System.out.println("**************");
}
}
}


这里我向数组列表添加两个对象。最后我尝试在主类函数中显示这两个元素。

但是该元素没有被添加。万一添加两个对象后它告诉我数组列表的大小为 0,并且不显示任何元素。

所以请帮助我知道如何才能得到想要的结果。

最佳答案

在列出其中的所有员工之前,您尚未将任何员工实例添加到 EmployeeDB 中。相反,您将它们添加到不同的 EmployeeDB 实例中。尝试下面的代码片段。

public static void main(String[] args) {
System.out.println(" ");

Employee e1 = new Employee(111,"Employee-1","loc-1",100);
Employee e2 = new Employee(222,"Employee-2","loc-2",200);

EmployeeDB x = new EmployeeDB();
x.addEmployee(e1);
x.addEmployee(e2);
Employee[] arr = x.listAll();

for(Employee e : arr){
System.out.println( e.eid );
System.out.println( e.eName );
System.out.println( e.eAddr );
System.out.println("**************");
}
}

关于java - 将对象存储在 arraylist 中并返回这些对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59441483/

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