
在java中,当尝试打印包含自定义对象的数组时,`arrays.tostring()`默认会输出对象的哈希码而非其内部数据。本教程将深入探讨这一现象的原因,并提供一个标准的解决方案:通过在自定义类中重写`tostring()`方法,实现对象内容的清晰、可读性强的输出,从而有效解决打印时只显示哈希码的问题,提升代码的可读性和调试效率。
在Java中,每个类都直接或间接继承自java.lang.Object类。Object类提供了一个默认的toString()方法,其实现通常返回一个字符串,格式为:类名@对象的哈希码的无符号十六进制表示。例如,com.example.Student@1b6d3586。
当您使用System.out.println()打印一个对象时,或者像在示例代码中那样,使用Arrays.toString()打印一个对象数组时,Java运行时会调用每个对象的toString()方法来获取其字符串表示。如果您的自定义类(例如Student类)没有重写toString()方法,那么它将继承Object类的默认实现,从而导致输出的是对象的哈希码,而不是我们期望的包含其字段值的可读内容。
考虑以下Student类定义,它缺少自定义的toString()方法:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
private static class Student {
String fName; // First Name
String lName; // Last Name
int id; // Student ID
int score; // Score
public Student(String fName, String lName, int id, int score) {
this.fName = fName;
this.lName = lName;
this.id = id;
this.score = score;
}
public int getScore() {
return score;
}
// 此处缺少自定义的 toString() 方法
}
// ... (其他辅助方法和 main 方法) ...
public static void main(String[] args) {
// ... (学生数据输入逻辑) ...
Student[] students = {
new Student("Mo", "Nee", 1, 900),
new Student("Lee", "Jen", 2, 600)
};
class ByScoreComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return Integer.compare(s1.getScore(), s2.getScore());
}
}
Arrays.sort(students, new ByScoreComparator());
// 此时,如果 Student 类没有重写 toString(),将打印哈希码
System.out.println(Arrays.toString(students));
}
}运行上述代码,其输出可能类似: [Main$Student@1b6d3586, Main$Student@4554617c] 这显然不是我们想要的学生信息。
要解决这个问题,您需要在自定义类中重写toString()方法。通过重写,您可以定义一个返回对象有意义的字符串表示形式的逻辑。当System.out.println()或Arrays.toString()再次调用此方法时,它将使用您定义的逻辑来生成输出。
立即学习“Java免费学习笔记(深入)”;
以下是如何在Student类中重写toString()方法:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
private static class Student {
String fName; // First Name
String lName; // Last Name
int id; // Student ID
int score; // Score
public Student(String fName, String lName, int id, int score) {
this.fName = fName;
this.lName = lName;
this.id = id;
this.score = score;
}
public int getScore() {
return score;
}
/**
* 重写 toString() 方法,提供 Student 对象的字符串表示
* @return 包含学生ID、姓名和分数的字符串
*/
@Override
public String toString() {
return "id: " + this.id + ", fName: " + this.fName + ", lName: " + this.lName + ", score: " + this.score;
}
}
// 检查字符串是否全为字母
public static boolean alphabetic(String str) {
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (!Character.isLetter(c))
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println("Enter the number of students");
Scanner input = new Scanner(System.in);
int k = input.nextInt(); // number of students
Student[] students = new Student[k];
for (int i = 0; i < k; ) {
System.out.println("Enter id");
int id = input.nextInt();
String fName;
do {
System.out.println("Enter first name ");
fName = input.next();
if (!alphabetic(fName)) {
System.out.println("Wrong! Please enter again ");
}
} while (!alphabetic(fName));
String lName;
do {
System.out.println("Enter last name ");
lName = input.next();
if (!alphabetic(lName)) {
System.out.println("Wrong! Please enter again ");
}
} while (!alphabetic(lName));
System.out.println("Enter score ");
int score = input.nextInt();
students[i++] = new Student(fName, lName, id, score);
}
// 定义按分数排序的比较器
class ByScoreComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return Integer.compare(s1.getScore(), s2.getScore());
}
}
Arrays.sort(students, new ByScoreComparator());
// 此时,由于 Student 类已重写 toString(),将打印对象内容
System.out.println(Arrays.toString(students));
input.close();
}
}通过添加上述toString()方法,当您再次运行程序并打印students数组时,输出将变为可读的学生信息:
[id: 2, fName: Lee, lName: Jen, score: 600, id: 1, fName: Mo, lName: Nee, score: 900]
(请注意,示例输出中的顺序可能因排序逻辑和输入数据而异,此处仅展示格式。)
在Java中,为了使自定义对象的打印输出更具可读性和实用性,重写Object类的toString()方法是必不可少的。通过提供一个清晰、有意义的字符串表示,不仅可以改善程序的可读性,还能在开发和调试过程中提供极大的便利。遵循上述最佳实践,可以确保您的Java代码更加健壮和易于维护。
以上就是Java自定义类toString()方法:实现对象内容的优雅打印的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号