[英]How to access an ArrayList from another class
I'm trying to find a way to copy the contents from an ArrayList in a class of mine to the class I am currently working in. 我正在尝试找到一种方法将内容从我的类中的ArrayList复制到我目前正在使用的类中。
This is how my code is currently looking in the class I want the contents to be transferred to: 这就是我的代码当前在类中我希望将内容传输到的方式:
MainActivity MA = new MainActivity();
ArrayList<String> deletedValues = new ArrayList<String>();
for(String item :MA.deletedItems){
deletedValues.add(item);
}
Also, the ArrayList in the MainActivity has the modifier private if that matters 此外,如果重要,MainActivity中的ArrayList具有私有修饰符
The code above does not cause any errors but will not return any values to the new ArrayList, deletedValues. 上面的代码不会导致任何错误,但不会将任何值返回给新的ArrayList,deletedValues。
You can make a get method in whatever class contains the arraylist like so: 您可以在任何包含arraylist的类中创建get方法,如下所示:
public ArrayList getDeletedValues() {
return deletedValues;
}
That is how you normally access private variables. 这就是您通常访问私有变量的方式。
Have a look at the Getters and Setters
design pattern. 看看
Getters and Setters
设计模式。 It means you can have your variables private whilst providing access to them for other classes in a manner you can control. 这意味着您可以将变量设置为私有,同时以您可以控制的方式为其他类提供访问权限。 Generally a typical class using
getters and setters
would look a little like this: 通常,使用
getters and setters
的典型类看起来有点像这样:
public class MyClass {
private int myInt;
// Setter
public void setMyInt(int value) {
myInt = value;
}
// Getter
public int getMyInt() {
return myInt;
}
}
When implemented in context you gave, you can expect your code to look similar to this, with your getters and setters in the MainActivity
class looking like the above example. 在您提供的上下文中实现时,您可以期望您的代码看起来与此类似,
MainActivity
类中的getter和setter类似于上面的示例。
MainActivity MA = new MainActivity();
ArrayList<String> deletedValues = new ArrayList<String>();
for(String item :MA.getDeletedItems()){
deletedValues.add(item);
}
However I will take this opportunity to point out that rather than creating a new instance of your MainActivity
class, you would probably find it much more beneficial to pass the current instance of the MainActivity
class to the class you are using through the means of a constructor or similar. 但是,我将借此机会指出,除了创建
MainActivity
类的新实例之外,您可能会发现通过构造函数将MainActivity
类的当前实例传递给您正在使用的类更有益或类似的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.