如何将对象从ArrayList传输到LinkedList

时间:2015-09-20 11:58:45

标签: java

我需要将我在ArrayList中获得的所有数据传输到LinkedList并显示所有这些,就像我使用ArrayList一样。当我将数据传输到LinkedList时,我无法显示它。代码如下:

import javax.swing.*;
import java.util.*;

public class testEmployee
{
    public static void main (String [] args)
    {
        ArrayList <Employee> empArray = new ArrayList();
        LinkedList yrIncm = new LinkedList();

    Employee emp;
    int empNum;
    boolean found = true;

    empNum = Integer.parseInt(JOptionPane.showInputDialog ("How many employees information do you want to store?"));

    for (int i = 0; i < empNum; i++)
    {
        String sEmpId = JOptionPane.showInputDialog ("Please enter the employee's ID");
        String sEmpName = JOptionPane.showInputDialog ("Please enter the employee's Name");
        String sEmpPosition = JOptionPane.showInputDialog ("Please enter the employee's position");
        Double dSalary = Double.parseDouble (JOptionPane.showInputDialog ("Please enter the employee's monthly salary"));

        emp = new Employee (sEmpId, sEmpName, sEmpPosition, dSalary);

        empArray.add (emp);
    }

    System.out.println ("Employee that obtains a monthly salary more than RM 2000.00");
    System.out.println ("===========================================================");
    for (int i = 0; i<empArray.size(); i++)
    {
        if (empArray.get(i).getSalary() > 2000)
        {
            empArray.get(i).display(); // This will display the info using ArrayList
        }
    }

    System.out.println ("\nEmployee that have yearly income greater than RM 80,000");
    System.out.println ("=======================================================");
    for (int i = 0; i<empArray.size(); i++)
    {
        if ((empArray.get(i).getSalary() * 12) > 80000)
        {

            yrIncm.add (empArray.get(i)); // Is this the correct way of transferring the data? 

            System.out.println (yrIncm); // How do you print it all back? 
        }
    }

   }
}

Employee类中的display()

public void display()
{
    System.out.println ("\nEmployee's ID : " + sEmpId);
    System.out.println ("Employee's Name : " + sEmpName);
    System.out.println ("Employee's Position : " + sEmpPosition);
    System.out.println ("Employee's Salary : RM " + df.format (dSalary));
}

我无法使用方法display()将其从LinkedList打印出来。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

for (int i = 0; i<empArray.size(); i++)
{
    if ((empArray.get(i).getSalary() * 12) > 80000)
    {
        LinkedList yrIncm = new LinkedList();

每次都创建一个新的链接列表,并将一个元素放入其中。然后打印出单元素列表并将其丢弃。

虽然上述情况肯定是错误的,但我看不到你想象中display()进入这张照片。您的链接列表永远不会离开for循环。

答案 1 :(得分:1)

您可以使用LinkedList.addAll获取ArrayList的所有元素。

LinkedList<Employee> yrIncm = new LinkedList();

yrIncm.addAll(empArray);
yrIncm.forEach(employee -> employee.display());

您的代码的问题在于您每次都在重新创建LinkedList,并且可能尝试在链接列表而不是员工对象上调用display()。