【问题标题】:How to get access to an object in the list from other class?如何从其他类访问列表中的对象?
【发布时间】:2016-05-11 12:03:21
【问题描述】:

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

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,但问题仍然存在。

【问题讨论】:

  • 您的“数据”是私有的,除非您实现 getter 和 setter,否则您无法在课堂外访问它......无论如何,您的课程设计似乎有点混乱
  • 您是否忘记在list.get(0).data[0] = "999" 行尾添加分号?
  • 将其更改为公开,但并没有使错误消失。分号也不是问题。当我写 list.get(0) 时,intelliJ 甚至不接受“get”
  • 你们能提供MCVE吗?包括进口。 stackoverflow.com/help/mcve

标签: java class arraylist


【解决方案1】:

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

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

在客户类中

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

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

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

希望有所帮助。

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多