0

So I have a class called Employee in which I created an ArrayListfor in another class. I am trying to print the values of the list but they print each element's object reference. I forgot how to do this, I have tried looking it up elsewhere but can't seem to find an answer.

Here is the Employee Class:

public class Employee {

int employeeID;
String employeeName;

public Employee(int employeeId, String employeeName){
this.employeeID = employeeId;
this.employeeName  = employeeName;

}
...

Here is where I print my values:

public void printArrListValues() {

   for(Employee x: employeeList){

        System.out.println(x);
    }
//    Arrays.toString(employeeNameLst);

}

I did try using .toString() on x, however this did not solve the issue.

The console printed this to me:

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)

2 Answers2

3

When you pass an object to println, eventually, toString() will be called. Because you didn't override toString(), Employee inherited Object's toString() method, which is responsible for the output you see.

In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Override toString in Employee, and return the String you want visible when the Employee is printed.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Sorry I don't fully understand what I need to do. Do I need to go inside my Employee class and then create a `toString()` method that takes an `Employee` as an argument then print its content using `System.out.print()`? – Jesal Patel Jan 09 '15 at 23:38
  • Not quite right. Create a method with the signature `public String toString()` in `Employee`, no parameters. Use your instance variables `employeeID` and `employeeName` when creating a `String` that represents how you want the output, and _return_ that `String`; don't print it. The `println` method will print whatever is returned by `toString()`. – rgettman Jan 09 '15 at 23:43
  • Yes override toString() and make it return meaningful information. Joshua Bloch even cites this a good practice as it makes your class much more pleasant to use, especially with IDEs and testing. Some IDEs like Eclipse will even provide tools to override it for you. – tmn Jan 10 '15 at 05:49
0
  1. you can override the method toString in class employee
  2. or x.getter methods
abdotalaat
  • 735
  • 7
  • 10