安卓 Java对象指针
我有安卓 Java程序,我需要一个公共函数来修改rootA或rootB,方法是将rootList设置为我想要修改的
public List<String> rootList=new ArrayList<>();
public List<String> rootA=new ArrayList<>();
public List<String> rootB=new ArrayList<>();
public index;
public void f1()
{
select(rootA,3);
select(rootB,2);
}
public void select(List<string> ary, int x)
{
rootList=ary;
index=x;
func1();
}
public void func1()
{
rootList.remove(index);
rootList.add("hello");
}
函数f1、select和func1都在不同的类中,rootList、rootA、rootB、index都是全局函数,为了清楚起见,我在这里把它们全部放进去
我希望能够调用f1,并通过将rootList设置为rootA或rootB,让它使用相同的函数修改rootA或rootB。这能行吗?还是我需要用其他方法
谢谢
# 1 楼答案
将要修改的列表以及
index
和任何其他需要的信息作为func1
的参数传递。这消除了对全局状态的需要,全局状态通常是邪恶的,在Android上尤其邪恶