我有一个问题,我想设置并从android的setter和getter方法中获取ArrayList
。但我是Android和Java的新手,不知道该怎么做?任何人都可以帮我解决这个问题吗?
答案 0 :(得分:11)
示例 -
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();
}
}
答案 1 :(得分:4)
为了更好的封装/ OO设计,我会做以下
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());
}
}
答案 2 :(得分:2)
ArrayList<String> arrList = new ArrayList<String>();
public ArrayList<String> getArrList() {
return arrList;
}
public void setArrList(ArrayList<String> arrList) {
this.arrList = arrList;
}
答案 3 :(得分:1)
通常,getter和setter方法用于从
赋值变量和获取变量值There is not any difference of getter and setter methods for arraylist or for int of a class
ArrayList<String> arrList;
public ArrayList<String> getArrList() {
return arrList;
}
public void setArrList(ArrayList<String> arrList) {
this.arrList = arrList;
}
Int
相同int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
答案 4 :(得分:0)
我不熟悉android。 但是在JAVA中,如果你想使用set和get方法,你需要先声明List。
private List arrayList = new ArrayList();
public List getArrayList() {
return arrayList;
}
public void setArrayList(List arrayList) {
this.arrayList = arrayList;
}
答案 5 :(得分:0)
请试试这个
public static ArrayList<books> al = new ArrayList<books>();
books book=new books(id,name,type);
book1 b1=new book1(id,name,type);
al.add(book);
al.add(book1); //error at book1
答案 6 :(得分:-1)
试试这些
public ArrayList getArrayList() {
return arraylist;
}
public void setArrayList(ArrayList arraylist) {
this.arraylist = arraylist;
}