//ArrayListEx(main class)

import java.io.*;
import man.Phone;
import man.Person;
import java.util.*;

public  class ArrayListEx{

public static void main(String[] args){

Person p= new Person();
p.setName("yo");
ArrayList<Phone> pList = new ArrayList<Phone>();
Phone ph = new Phone();
ph.setOne("dasd");
pList.add(ph);
System.out.println("sgs "+pList);
}
}

My Program has a Person,Phone and ArrayListEx(main class) classes,Person contains an ArrayList<Phone> class but when printing the List of Phone from Person,the result is the address of the element instead of the actual element.

//Result:
sgs [man.Phone@4830c221]

Thanks.

man.Phone@4830c221

What you printed was the String returned by the Phone class's default toString() method. It is made of the full classname, @ and the object's hashcode(in hex).
If you want to change that String, you need to override the Phone class's toString() method and have it return the String with what you want to see printed.

but i did not assign a toString method to the Phone class,this is the Phone class:

package man;

import java.io.*;



public class Phone{

public String one;



public String getOne(){
return one;

}
public void setOne(String one)
{
this.one = one;

}


}

and this is the Person class:

ackage man;


import java.io.*;
import man.*;
import java.util.*;


public class Person{

public String name;
public ArrayList<Phone> ph= new ArrayList<Phone>();



public void setPhoneList(ArrayList<Phone> ph){
this.ph= ph;
}

public ArrayList<Phone> getPhoneList(){
return ph;

}

public String getName(){

return name;
}

public void setName(String name){
this.name = name;

}

Every Java class inherits a toString() method from the Object class, so methods like println use that to convert the object you want to print into a String. The inherited method prints the class name and the object's hash (normally the same as its address). If you want to display something more helpful, override the toString method in your class to return a useful string. Eg

class Person {
    private String givenName, familyName;
    ...
    public String toString() {
        return "Person: " + givenName + " " + familyName;
    }

You should do this for every class you create so when you print an instance you get useful output.

Thanks,I understand...and it works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.