I have a problem that I want to set and get an ArrayList
from setter and getter methods of android. But I am new to android and Java and don't know how to do that? Can anyone help me regarding this problem?
Example -
import java.util.ArrayList;
import java.util.List;
public class Test {
List<String> list = null;
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public static void main(String[] args) {
Test test = new Test();
List<String> sample = new ArrayList<String>();
sample.add("element 1");
test.setList(sample);
List<String> sample1 = test.getList();
}
}
For better Encapsulation / OO design I would do following
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestListGetterSetter {
List<String> list = new ArrayList<>();
//Return copy of the list
public List<String> getList() {
return new ArrayList<>(list);
}
// Copy source list into destination list
public void setList(List<String> listToBeSet) {
if (listToBeSet != null)
this.list.addAll(listToBeSet);
}
public static void main(String[] args) {
TestListGetterSetter testListGetterSetter = new TestListGetterSetter();
List<String> clientList = new ArrayList<>(Arrays.asList("foo", "bar", "HiHa"));
testListGetterSetter.setList(clientList);
System.out.println("TestListGetterSetter.list before clientList modification = " + testListGetterSetter.getList());
//Now you can change "clientList" without affecting testListGetterSetter object
clientList.add("1");
System.out.println("clientList modified List = " + clientList);
System.out.println("TestListGetterSetter.list after clientList modification = " + testListGetterSetter.getList());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With