我正在尝试打印出我创建的对象Teacher的数组,并且它给了我一个奇怪的输出。 [老师@ 659e0bfd,老师@ 2a139a55,老师@ 15db9742,老师@ 6d06d69c,老师@ 7852e922] 在我尝试在2d数组上使用toString()之前我遇到过这个问题,但我现在使用的是1d对象数组。我已经尝试过使用deepToString()和toString(),但它仍然提供这样的输出。我试着查找如何打印出一个对象数组,但我找到的只是如何打印出常规数组。
我的代码:
import java.util.Arrays;
public class Main {
public static void main(String[] args){
Teacher[] teachers = new Teacher[5];
Student[] students = new Student[25];
createTeacherNames(teachers);
System.out.println(Arrays.toString(teachers));
}
public static void createTeacherNames(Teacher[] teachers){
teachers[0] = new Teacher("Mrs.", "Smith", 201);
teachers[1] = new Teacher("Mr.", "Johnson", 202);
teachers[2] = new Teacher("Mrs.", "Williams", 203);
teachers[3] = new Teacher("Mr.", "Brown", 204);
teachers[4] = new Teacher("Mr.", "Jones", 205);
}
}
人类:
public class Person {
public String firstName;
public String lastName;
public Person(String firstName, String lastName){
this.setFirstName(firstName);
this.setLastName(lastName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
教师班:
public class Teacher extends Person {
public int roomNumber;
public Teacher(String firstName, String lastName, int roomNumber) {
super(firstName, lastName);
}
}
学生班:
public class Student extends Person {
public Student(String firstName, String lastName, int studentIdNumber, double GPA) {
super(firstName, lastName);
}
}
答案 0 :(得分:2)
您应该创建自定义toString()
方法(覆盖toString()
类的默认Teacher
方法)。 Teacher@659e0bfd
是对象标识符,由对象的默认toString()
方法返回。
它可能看起来像这样:
public String toString()
{
return super.getFirstName() + " " super.getLastName() + " " + this.roomNumber;
}
答案 1 :(得分:2)
在您的Teacher类中,覆盖toString(),类似于:
@Override
public String toString() {
String out = "";
out = "[" + teacherPrefix + "," + firstName + "," + idNum + "]";
return out;
}
会返回类似的内容:
//[Mrs.,Smith,201]
使用StringBuilder可能更好,但是你可以从我的例子中找出你需要的东西。