我有一个类,它启动String类型的数组列表。然后我将一些伪数据添加到这个数组中。
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();
}
}
在一个单独的班级里。然后我调用这个arraylist并向它添加更多数据。然而,在这个不同的类中,数组是空的
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);
}
}
--从Home类输出没有组1测试的响应。在这个不同的类别中,我指的Group_Customers是错的吗?感谢所有的帮助。感谢
调用Home h = new Home();
时,使用默认构造函数实例化一个新的Home
。
如果希望数组包含数据,请确保在构造函数中添加伪数据。此外,实际的代码不会编译,不能只在类主体中抛出方法调用。
你会有这样的东西:
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);
}
}
请注意,按照惯例,变量应在每个单词处以小写和大写开头,因此应将变量重命名为groupCustomers
。