从数组中提取对象的所有元素

时间:2019-12-21 19:09:19

标签: java collections


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[] arr =(Employee) al.toArray();
        return arr;
    }
}



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


        Employee[] arr = new Employee[2];

        Employee e1 = new Employee(111,"Employee-1","loc-1",100);
        EmployeeDB d1 = new EmployeeDB();
        d1.addEmployee(e1);
        arr[0] = d1.listAll();

        Employee e2 = new Employee(222,"Employee-2","loc-2",200);
        EmployeeDB d2 = new EmployeeDB();
        d2.addEmployee(e2);
        arr[1] = d2.listAll();


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


有人可以帮助我吗? 在这里,我想看看我的对象是否已添加到Arraylist中。 我试图提取这些细节,但在这里我一次又一次失败。 请告诉我我做错了什么? ........ ........ ........ ....... ...... ....... .......

1 个答案:

答案 0 :(得分:0)

尝试

    public Employee[] listAll() {
        Employee[] array = new Employee[al.size()];
        return al.toArray(array);
    }