0

I want to add a name to a list with composition. What am I doing wrong here? Also, if i wanted to add more than just a name, would adding another field to the Customer class do the trick? (Even if it is something else than a String?)

public class Main {
private static Customer cus;    
private static Firstclass fc = new Firstclass(cus);    

public static void main(String[] args) {

        fc.addFirstClass("John");
        System.out.println("The list of FirstClass passengers is " + fc.getFirstClass());
    }

public class Firstclass {

    private Customer customer;
    private ArrayList<Customer> firstClass;

    public Firstclass(Customer customer) {
        this.firstClass = new ArrayList<>();
        this.customer = customer;
    }

    public void addFirstClass(String name) {
        firstClass.add(new Customer(name));
        System.out.println(name + " was added to firstclass.");
    }

    public ArrayList<Customer> getFirstClass() {
        return firstClass;
    }
}


public class Customer {

    private String name;

    public String getName() {
        return name;
    }

    public Customer(String name) {
        this.name = name;
    }
}
Magne
  • 1
  • 2
  • 2
    And your question is what exactly? I am not getting either the point of doing this or the problem you're facing. – akortex May 05 '19 at 20:47
  • Im trying to learn how to use composition and Lists. New to coding. When i run the program it prints "The list of FirstClass passengers is [com.company.Customer@1cd072a9]" – Magne May 05 '19 at 20:50
  • override `toString()` method in `Customer` class with desired output https://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java – Ryuzaki L May 05 '19 at 20:51
  • Yeah and it's to be expected. When you attempt to print the list you are effectively printing out the memory reference of the object. If you want to print the contents then you'll have to iterate it. Your problem had nothing to do with composition. – akortex May 05 '19 at 20:56
  • Wow. That simple method solved everything. Thanks a lot mate! – Magne May 05 '19 at 21:12

0 Answers0