如何从其他类访问列表中的对象?

时间:2016-05-11 12:03:21

标签: java class arraylist

我在某个类的数组列表中有一个对象列表:

public class Customer implements barber.barberapp.crud {
private String[] data = {"id", "imie", "nazwisko", "email", "tel"};

public static List<Customer> getClients(){
    List<Customer> list = new ArrayList<Customer>();

    Customer c1 = new Customer("001", "Adam", "Nowak", "an@wp.pl","123");
    list.add(c1);

    list.get(0).data[0] = "999"; //checking if accessing object works correctly

    return list;
    }
}

现在,当我尝试访问其他类中的列表时,我收到错误“无法解析符号获取”。

public class CustomerListActivity extends AppCompatActivity {
    List<Customer> list = Customer.getClients();
    list.get(0).data[0] = "999" //error here
}

编辑:getClients方法返回List&lt;客户&gt;现在,但问题仍然存在。

1 个答案:

答案 0 :(得分:0)

您的代码除非是实例变量,否则需要进入方法。因此,在getData()课程中实施getter(Customer)后,请尝试以下操作:

public class CustomerListActivity extends AppCompatActivity {
    List<Customer> list = Customer.getClients();
    public void yourMethod(){
        list.get(0).getData()[0] = "999";
    }
}

在Customer类中

public String[] getData(){
     return data;
}

那说你可能想重新设计你的类,因为它看起来有点奇怪,请注意你应该为Customer类提供一个显式的构造函数,因为这是你创建Customer实例的方法

Customer c1 = new Customer("001", "Adam", "Nowak", "an@wp.pl","123");

希望有所帮助。