user904976
user904976

Reputation:

Nested ArrayList : Accessing private members

This is a homework problem that i have been asked to do.

Create an outer ArrayList and insert two ArrayList into it.

ArrayList<Customer> customers1 = new ArrayList<Customer>();
ArrayList<CustomerOtherDetails> customers2 = new ArrayList<CustomerOtherDetails>();
ArrayList<ArrayList> outerList = new ArrayList<ArrayList>();

These are the three ArrayList which are created, there are two separate sample classes Customer and CustomerOtherDetails which are present. I would be adding the reference variables to both arrayLists (customers1 and customers2) by doing customers1.add(customer) etc. I am asked to do sample things like adding a new customer, searching a new customer, sorting etc. all of this from the nested ArrayList

The problem i am facing currently is that i am unable to print details of values pointed by the reference variables in my array list.

When i try to print out values using get(), i am only able to print out like this

[[new.Customer@3972aa3f], [new.advanced.CustomerOtherDetails@17072b90]]

Upvotes: 2

Views: 143

Answers (1)

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15209

You need to override the public String toString() method in your Customer class and CustomerOtherDetails class.

This is how you'd do it:

public class Customer { 
     // ... other code

    @Override
    public String toString() {
        return "Customer: " + ... ; // append instance variable values here
    }
}

The toString method is defined in the base Object class that all other classes inherit from in Java. It gets implicitly called whenever you try to convert an object to a String, for example through System.out.println.

Upvotes: 5

Related Questions