如何在字符串中打印出数组列表的值?
How do I print out values of an array list in string?
所以我有一个名为 Employee 的 class,我在另一个 class 中创建了一个 ArrayList
for。我正在尝试打印列表的值,但它们打印了每个元素的对象引用。我忘了怎么做,我试过在别处查找但似乎找不到答案。
这是员工 Class:
public class Employee {
int employeeID;
String employeeName;
public Employee(int employeeId, String employeeName){
this.employeeID = employeeId;
this.employeeName = employeeName;
}
...
这是我打印值的地方:
public void printArrListValues() {
for(Employee x: employeeList){
System.out.println(x);
}
// Arrays.toString(employeeNameLst);
}
我曾尝试在 x 上使用 .toString()
,但这并没有解决问题。
控制台打印给我:
binarytree.Employee@78da5318
binarytree.Employee@45858aa4
binarytree.Employee@425138a4
binarytree.Employee@625db8ff
binarytree.Employee@771c9fcc
binarytree.Employee@783f472b
binarytree.Employee@25995ba
binarytree.Employee@4774e78a
BUILD SUCCESSFUL (total time: 0 seconds)
当您将对象传递给 println
时,最终会调用 toString()
。因为你没有覆盖toString()
,Employee
继承了Object
's toString()
method,它负责你看到的输出。
In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
覆盖 Employee
中的 toString
,并且 return 您希望在打印 Employee
时可见的 String
。
- 您可以覆盖 class 员工中的 toString 方法
- 或x.getter方法
所以我有一个名为 Employee 的 class,我在另一个 class 中创建了一个 ArrayList
for。我正在尝试打印列表的值,但它们打印了每个元素的对象引用。我忘了怎么做,我试过在别处查找但似乎找不到答案。
这是员工 Class:
public class Employee {
int employeeID;
String employeeName;
public Employee(int employeeId, String employeeName){
this.employeeID = employeeId;
this.employeeName = employeeName;
}
...
这是我打印值的地方:
public void printArrListValues() {
for(Employee x: employeeList){
System.out.println(x);
}
// Arrays.toString(employeeNameLst);
}
我曾尝试在 x 上使用 .toString()
,但这并没有解决问题。
控制台打印给我:
binarytree.Employee@78da5318
binarytree.Employee@45858aa4
binarytree.Employee@425138a4
binarytree.Employee@625db8ff
binarytree.Employee@771c9fcc
binarytree.Employee@783f472b
binarytree.Employee@25995ba
binarytree.Employee@4774e78a
BUILD SUCCESSFUL (total time: 0 seconds)
当您将对象传递给 println
时,最终会调用 toString()
。因为你没有覆盖toString()
,Employee
继承了Object
's toString()
method,它负责你看到的输出。
In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
覆盖 Employee
中的 toString
,并且 return 您希望在打印 Employee
时可见的 String
。
- 您可以覆盖 class 员工中的 toString 方法
- 或x.getter方法