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 any开发者_运维问答one 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());
}
}
ArrayList<String> arrList = new ArrayList<String>();
public ArrayList<String> getArrList() {
return arrList;
}
public void setArrList(ArrayList<String> arrList) {
this.arrList = arrList;
}
Generally getter and setter methods are for assign variable and get variables value from that
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;
}
Same for Int
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
I am not familiar with android. But in JAVA, if you want to use set and get method, you need to declare the List first.
private List arrayList = new ArrayList();
public List getArrayList() {
return arrayList;
}
public void setArrayList(List arrayList) {
this.arrayList = arrayList;
}
please try this
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
Try these
public ArrayList getArrayList() {
return arraylist;
}
public void setArrayList(ArrayList arraylist) {
this.arraylist = arraylist;
}
精彩评论