'Printing a 2D ArrayList in Java returns the length on one line
I need to print a 2D ArrayList. I have it set up like this:
static ArrayList <Employee> employeeList = new ArrayList <>();
public static class Employee extends Object {
//Attributes
String id, firstName, lastName, annualSalary, startDate;
//Constructor
public Employee(String id, String firstName, String lastName, String annualSalary, String startDate) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.annualSalary = annualSalary;
this.startDate = startDate;
}
//Getters or Accessors
public String getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAnnualSalary() {
return annualSalary;
}
public String getStartDate() {
return startDate;
}
@Override
public String toString() {
return id + " " + firstName + " " + lastName + " " + annualSalary + " " + startDate;
}
}
...
public static void printArrayList() {
for (int x=0; x<employeeList.size(); x++) {
for (int y=0; y<=0; y++) {
System.out.print(employeeList);
}
System.out.print ("\n \n");
}
}
When I do this, if there is one element in the list it prints:
[12345 john henry 100000 01/01/2000]
However, when I have 2 elements, it prints:
[12345 john henry 100000 01/01/2000, 67890 frank longman 125000 12/31/1999]
[12345 john henry 100000 01/01/2000, 67890 frank longman 125000 12/31/1999]
When there are 2 elements, I want it to print:
[12345 john henry 100000 01/01/2000]
[67890 frank longman 125000 12/31/1999]
How do I fix this?
Solution 1:[1]
First, that's not a 2D ArrayList, a 2D ArrayList would look like ArrayList<ArrayList<Employee>>. You are printing the entire list every iteration instead of one item each. Also, you can use System.out.println() instead of System.out.print() to add a new line after every print:
public static void printArrayList() {
for (int i = 0; x < employeeList.size(); i++) {
System.out.println(employeeList.get(i));
}
}
If you want to add an empty line between every print yo can modify previous method to:
public static void printArrayList() {
for (int i = 0; x < employeeList.size(); i++) {
System.out.println(employeeList.get(i) + System.lineSeparator());
}
}
If you want to surround every Employee with [], you can modify the toString() method in Employee class:
@Override
public String toString() {
return "[" + id + " " + firstName + " " + lastName
+ " " + annualSalary + " " + startDate + "]";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
