Mọi người cho em hỏi cách hoạt động của hàm toString như thế nào ạ? ngoài dùng để in mảng thì nó còn làm gì không ạ?
@Override
public String toString() {
String s = "";
for (int i = 0; i < n;)
s = s + a[i] + " ";
return s;
}
Mọi người cho em hỏi cách hoạt động của hàm toString như thế nào ạ? ngoài dùng để in mảng thì nó còn làm gì không ạ?
@Override
public String toString() {
String s = "";
for (int i = 0; i < n;)
s = s + a[i] + " ";
return s;
}
toString bản chất là một hàm trong class Object của Java dùng để in giá trị của object nếu bạn dùng lệnh in như
Object object = new Object();
System.out.println(object); // object@xxxxx - xxxxx là mã hash của object
Source code hàm Object.toString()
/**
* Returns a string representation of the object. In general, the
* {@code toString} method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
* <p>
* The {@code toString} method for class {@code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{@code @}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Mọi class trong Java đều mặc định extends class Object này nên bạn có quyền được override hàm toString để in giá trị object theo ý muốn
VD cho việc custom hàm toString theo ý muốn
public class Student {
private Long id;
private String firstName;
private String lastName;
private Integer age;
private Sex sex; // Sex enum: MALE and FEMALE
private String address;
private String phoneNumber;
private String email;
private Long classId;
// Getters and Setters here...
@Override
public String toString() {
return String.format("{ id: %s, firstName: %s, lastName: %s, age: %d, sex: %s, address: %s, phoneNumber: %s, email: %s, classId: %d }", id, firstName, lastName, age, sex.toValue(), address, phoneNumber, email, classId);
}
}
Hàm main
public static void main(String[] args) {
Student std = new Student();
std.setId(1L);
std.setFirstName("Van A");
std.setLastName("Nguyen");
std.setAge(18);
std.setSex(Sex.MALE);
std.setAddress("HCMC");
std.setPhoneNumber("01234567890");
std.setEmail("[email protected]");
std.setClassId(1);
System.out.println(std); // { id: 1, firstName: Van A, lastName: Nguyen, age: 18, sex: Male, address: HCMC, phoneNumber: 01234567890, email: [email protected], classId: 1 }
}
em cảm ơn nhiều ạ, hàm này giúp mình tiết kiệm code :smiley
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?