user2287508
user2287508

Reputation: 9

How to print all the elements from a ArrayList?

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

Upvotes: 0

Views: 2212

Answers (6)

adarshr
adarshr

Reputation: 62603

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);
    }
}

Upvotes: 0

Hut
Hut

Reputation: 33

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;
}

Upvotes: 0

hd1
hd1

Reputation: 34677

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.

Upvotes: 0

Muneeb Nasir
Muneeb Nasir

Reputation: 2504

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());

Upvotes: 0

Alexandre Wiechers Vaz
Alexandre Wiechers Vaz

Reputation: 1617

You can also, use a foreach to do it ;)

for(Auteur a: auteurs){
    System.out.print(a.getName() + " - " + a.getNumber());
}

Upvotes: 1

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18158

You need to override Autuer's toString method to return its contents in String format

Upvotes: 3

Related Questions