我需要将在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中将其打印出来。任何帮助,将不胜感激

最佳答案

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


您每次都创建一个新的链表,并将一个元素恰好放入其中。然后,您打印出一个元素列表并将其扔掉。

尽管以上内容肯定是错误的,但我看不到您在display()想象的位置输入这张图片。您的链表永远不会离开for循环。

关于java - 如何将对象从ArrayList传输到LinkedList,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32679126/

10-12 02:30