在 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]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP