1

I have class which initiates an arraylist of type String. I then add some dummy data into this array.

public class Main {

public static void main(String[] args)
    {
    Home h = new Home();
    h.add();
    }
}

public class Home
{
public ArrayList<String> Group_Customers= new ArrayList<String>();
public void add()
    {
        String[] group1 = {"0", "Mr", "Smith", "Andrew"}
        for(int i = 1; i < group1.length; i++)
        {
             Group_Customers.add(group1[i]);
        }
        Add_Booking a = new Add_Booking();
        a.Add();
    }
}

In a seperate class. I then call this arraylist and add more data to it. However the array is empty in this different class

public class Add_Booking
{
String Title;
String Firstname;
String Surname;
    public void add_Data
    {
        Title = "Mr";
        Firstname = "Bob";
        Surname = "Gallow";

        save_Data();
    }

    public void save_Data
    {
        Home h = new Home();
        String[] responses = {Title, Firstname, Surname};

        for(int i = 1; i < responses.length; i++)
        {
            h.Group_Customers.add(responses[i]);
        }
    System.out.println(h.Group_Customers);
    }
}

--Outputs responses without group1 test from class Home. Am I refering to Group_Customers wrong within this different class? All help appreciated. Thanks

0

1 Answer 1

3

When calling Home h = new Home(); you instantiate a new Home with the default constructor.

Make sure you add the dummy data in the constructor if you want the array to contains data. Also, the actual code would not compile, you can't just throw method call in class body.

You would have something like this :

public class Home
{
    //Declare the List
    public ArrayList<String> Group_Customers = null;

    //Default constructor
    public Home()
    { 
        //Instantiate and add dummy data
        Group_Customers = new ArrayList<String>();
        Group_Customers.add("test");
    }
}

public class Add_Booking
{
    public static void main(String args[])
    {
        //Construct a new home with default constructor.
        Home h = new Home();

        //Add new data
        h.Group_Customers.add("new data");

        //Display List content (should display test and new data)
        System.out.println(h.Group_Customers);
    }
}

Note that by convention, variable should start with a lower-case and an upper-case at each words so you should rename your variable as groupCustomers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.