是否可以使用 Java 覆盖数组中的 toString 方法?
javaobject oriented programmingprogramming更新于 2024/2/18 8:44:17
您可以覆盖 Object 类的 toString() 方法,但是,如果您正在创建特定类的对象数组,并希望通过覆盖 toString() 方法来打印此数组的内容,那么您无法做到这一点,因为目前 Java 中还没有解决方案。
但是您可以使用各种其他方法实现这一点 −
使用 Arrays 类的 toString() 方法
Arrays 类的 toString() 方法接受 String 数组(实际上是任何数组)并将其作为 String 返回。将您的 String 数组作为参数传递给此方法。您只需将您的对象数组传递给此方法即可。
示例
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]
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

