是否可以使用Java覆盖数组中的toString方法?
您可以覆盖Object类的toString()方法,但是,如果您要创建特定类的对象数组,并且想通过覆盖toString()方法而不是the来打印此数组的内容,则无法在该位置执行此操作。到目前为止,在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覆盖数组中的toString方法? 的全部内容, 来源链接: utcz.com/z/353522.html