Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Getter and Setter for arraylist in java

Tags:

android

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?

like image 820
Sanat Pandey Avatar asked Dec 02 '22 01:12

Sanat Pandey


2 Answers

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();
}
}
like image 193
Jayendra Avatar answered Dec 18 '22 16:12

Jayendra


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());
  }
}
like image 32
Farm Avatar answered Dec 18 '22 16:12

Farm