Friday, 13 September 2013

Another class interacting with variables in main method

Another class interacting with variables in main method

I have a main method which creates a List<Long>. I then have another class
whose state is a List<Long> - the goal of this class is to take in the
main method's List<Long> as its state and do manipulations to it without
affecting the main method's List<Long>.
However the problem that I am facing is that this other class is impact
both its state (its private List<Long>) as well as the List<Long> in the
main method.
How do I adjust my code such that setTesting(...) is only able to
influence the state of its class?
public class Main {
public static void main(String[] args) {
final List<Long> mainlist = new ArrayList<Long>();
mainlist.add((long) 1);
mainlist.add((long) 2);
mainlist.add((long) 3);
Test testlist = new Test();
testlist.setTesting(mainlist);
System.out.println(testlist.getTesting());
testlist.removal((long) 1);
System.out.println(testlist.getTesting());
}
}
public class Test {
private List<Long> testing = new ArrayList<Long>();
public Test() {
}
public void removal(Long remove) {
this.testing.removeAll(Collections.singleton(remove));
}
public void setTesting(List<Long> list) {
this.testing = list;
}
public List<Long> getTesting() {
return this.testing;
}
}

No comments:

Post a Comment