在 Java 中,是否可以重写数组的 toString 方法?
您可以重写 Object 类的 toString() 方法,但是,如果您正在创建一个特定类的对象数组,并且希望通过重写 toString() 方法来打印此数组的内容而不是使用默认方法,那么您无法做到这一点。目前 Java 中还没有针对此问题的解决方案。
但是,您可以使用其他多种方法来实现此目的:
使用 Arrays 类的 toString() 方法
Arrays 类的 toString() 方法接受一个字符串数组(实际上是任何数组),并将其作为字符串返回。将您的字符串数组作为参数传递给此方法。您可以简单地将您的对象数组传递给此方法。
示例
import java.util.Arrays; class Student { String name = "Krishna"; int age = 20; Student(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Name: "+this.name+" "+"Age: "+this.age; } } public class Example { public static void main(String args[]) { Student std1 = new Student("Krishna", 20); Student std2 = new Student("Radha", 25); Student std3 = new Student("Trupthi", 30); Student std4 = new Student("David", 35); Student std5 = new Student("Moksha", 40); Student students[] = {std1, std2, std3, std4, std5}; System.out.println(Arrays.toString(students)); } }
输出
[Name: Krishna Age: 20, Name: Radha Age: 25, Name: Trupthi Age: 30, Name: David Age: 35, Name: Moksha Age: 40]
使用 Arrays 类的 asList() 方法
此方法接受一个数组作为参数,并返回一个 List 对象。使用此方法将数组转换为 Set。
示例
import java.util.Arrays; class Student { String name = "Krishna"; int age = 20; Student(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Name: "+this.name+" "+"Age: "+this.age; } } public class Example { public static void main(String args[]) { Student std1 = new Student("Krishna", 20); Student std2 = new Student("Radha", 25); Student std3 = new Student("Trupthi", 30); Student std4 = new Student("David", 35); Student std5 = new Student("Moksha", 40); Student students[] = {std1, std2, std3, std4, std5}; System.out.println(Arrays.asList(students)); } }
输出
[Name: Krishna Age: 20, Name: Radha Age: 25, Name: Trupthi Age: 30, Name: David Age: 35, Name: Moksha Age: 40]
使用 ArrayList 类
这是一种稍微不同的解决方案:
创建一个扩展 ArrayList 类的类。
将对象添加到此类中。
使用 ArrayList 类的 toString() 方法打印内容。
示例
import java.util.ArrayList; import java.util.Arrays; class Student { String name = "Krishna"; int age = 20; Student(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Name: "+this.name+" "+"Age: "+this.age; } } public class Example extends ArrayList<Object> { public static void main(String args[]) { Example obj = new Example(); obj.add(new Student("Krishna", 20)); obj.add(new Student("Radha", 25)); obj.add(new Student("Trupthi", 30)); obj.add(new Student("David", 35)); obj.add(new Student("Moksha", 40)); System.out.println(obj.toString()); } }
输出
[Name: Krishna Age: 20, Name: Radha Age: 25, Name: Trupthi Age: 30, Name: David Age: 35, Name: Moksha Age: 40]
广告