gpt4 book ai didi

java - 集合对象无法显示在 java、Arraylist、集合中显示某些未定义值的输出

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:25:28 24 4
gpt4 key购买 nike

当我尝试打印集合对象时,它打印出 Employee@122392Iie92。为什么要打印这个而不是员工列表的详细信息?

我的代码:

    public class Employee {

private String name;
private String designation;
private int employeeId;
private int salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}

}

import java.util.ArrayList;

import java.util.Scanner;


public class EmployeeManagement {
static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
// TODO Auto-generated method stub

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

System.out.println("Enter the number of employees : ");

int num = sc.nextInt();

EmployeeManagement emp = new EmployeeManagement();

emp.addEmployeeName( num, lst);


}

public void addEmployeeName(int num,ArrayList<Employee> lst) {

Employee em = new Employee();

for(int i =0; i<num ; i++)
{
System.out.println("Enter the employee id : ");
em.setEmployeeId(sc.nextInt());

System.out.println("Enter the name of employee : ");
em.setName(sc.next());

System.out.println("Enter the designation of employee : ");
em.setDesignation(sc.next());

System.out.println("Enter the Salary of employees : ");
em.setSalary(sc.nextInt());

lst.add(em);
}

System.out.println(lst);
}

}

最佳答案

它使用 Object 类的默认 toString 方法进行打印。如果您想显示值,您需要覆盖 Employee 类中的 toString。它当前显示类名和哈希码。

在 Employee 中写一个这样的 toString 方法:

 @Override
public String toString(){
SubString sb = new SubString();
sb.append("Name :- ")append(name).append(id); //all relevant fields
return sb.toString();
}

在循环内移动新语句,否则您将一次又一次地添加和更新同一个对象。

 public void addEmployeeName(int num,ArrayList<Employee> lst) {



for(int i =0; i<num ; i++)
{
Employee em = new Employee();
System.out.println("Enter the employee id : ");
em.setEmployeeId(sc.nextInt());

System.out.println("Enter the name of employee : ");
em.setName(sc.next());

System.out.println("Enter the designation of employee : ");
em.setDesignation(sc.next());

System.out.println("Enter the Salary of employees : ");
em.setSalary(sc.nextInt());

lst.add(em);
}

System.out.println(lst);
}

}

关于java - 集合对象无法显示在 java、Arraylist、集合中显示某些未定义值的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27402757/

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