2

I wanna convert the linked list to array. But when I print it it gives me the objects' hash code. How can I fix this? I create an array and then equalize it to the person object which is in the linked list.

Person [] personArray;
personArray = new Person[phoneList.size()];
System.out.println(personArray);

Phone Book Class:

public class PhoneBook
{

Scanner input = new Scanner(System.in);
SLinkedList<Person> phoneList;
Person [] personArray;

public PhoneBook(){
    phoneList = new SLinkedList<Person>();
}

public void addPerson(){
    System.out.println("Create new person.");
    System.out.println("Name: ");
    String name = input.next();

    System.out.println("Surname: ");
    String sn = input.next();

    System.out.println("Address: ");
    String a = input.next();

    System.out.println("Cell Number: ");
    int cell = input.nextInt();

    System.out.println("Home Number: ");
    int hn = input.nextInt();

    System.out.println("Work Number: ");
    int wn = input.nextInt();

    Person per = new Person(name, sn, a, cell, hn, wn); 
    phoneList.addLast(per);
    personArray = new Person[phoneList.size()];
    System.out.println(personArray);

}

Person class :

public class Person
{
    private String name;
    private String surname;
    public  String address;
    public int cell;
    public int home;
    public int work;


    public Person(String name, String surname, String address, int cell, int home, int work){
        this.name    = name;
        this.surname = surname;
        this.address = address;
        this.cell    = cell;
        this.home    = home;
        this.work    = work;
    }

    // Accessor methods:
    public String getName(){
        return name;
    }
    public String getSurname(){
        return surname;
    }
    public String getAddress(){
        return address;
    }
    public int getCell(){
        return cell;
    }
    public int getHome(){
        return home;
    }
    public int getWork(){
        return work;
    }

    // Modifier methods:
    public  void setName(String name){
        this.name = name;
    }
    public void setSurname(String surname){
        this.surname = surname;
    }
   public void setAddress (String address){
        this.address = address;
    }
    public void setCell (int cell){
        this.cell = cell;
    }
    public void setHome (int home){
        this.home = home;
    }
    public void setWork (int work){
        this.work = work;
    }

    public String toString(){
        return name + " " + surname + " " + address + " " + cell + " " + home + " " + work;
    }
}
rumay
  • 65
  • 7

1 Answers1

1

Use Arrays.toString:

personArray = new Person[phoneList.size()];
//here you should add code that actually copies the elements of the list to 
//the array. Otherwise, the array would be empty
System.out.println(Arrays.toString(personArray));
Eran
  • 387,369
  • 54
  • 702
  • 768