I'm trying to print all the element I have added to my arraylist, but it only prints the adress and not the string.
Can someone help me or give out some tips? I've been searching all afternoon
您需要重写Autuer的toString方法以String格式返回其内容
You can also, use a foreach to do it ;)
for(Auteur a: auteurs){
System.out.print(a.getName() + " - " + a.getNumber());
}
Every object in Java inherits
public String toString();
from java.lang.Object
in your Auteur
class you need to write some code similar to the following:
.... ....
@Override
public String toString() {
return "Name: "+this.name;
}
Try defining the toString()
method in your Auter
class as follows:
public String toString() {
return this.getName() + " - " + this.getNumber());
}
and your code will do what you wish. System.out.println
calls the argument's toString()
method and prints that out to the Output console.
itr.next()
returns object of Auteur
rather than String
. To print the name you need to type cast it with Auteur
and then print it if you have a print method for the class Auteur
.
Auteur aut = (Auteur) itr.next();
System.out.println(aut.printMethod());
What you see is called the default toString of an object. It is an amalgamation of the FQCN (fully qualified class name) of the class it belongs to and the hashCode of the object.
Quoting from the JavaDoc of toString:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', 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:
getClass().getName() + '@' + Integer.toHexString(hashCode())
We can override toString
to give a more human readable output. Take a look at the below two classes, with and without toString
. Try to execute the main method and compare the output of the two print statements.
class Person {
private String name;
@Override
public String toString() {
return "Person [name=" + this.name + "]";
}
}
class Address {
private String town;
}
public class Test {
public static void main(String... args) {
Person person = new Person();
Address address = new Address();
System.out.println("Person is : " + person);
System.out.println("Address is : " + address);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.