我是java新手,我正在尝试访问与其他类不同的类中的ArrayList和TreeSet。 我知道这种从一个类访问它的方式。
这是我拥有 TreeSet 的类(class):
public class Gestor {
private TreeSet<User> gestorTSusers;
public Gestor (){
this.gestorTSusers = new TreeSet<>();
}
public TreeSet<User> getGestorTSusers() {
return gestorTSusers;
}
public void setGestorTSusers(TreeSet<User> gestorTSusers) {
this.gestorTSusers = gestorTSusers;
}
}
现在我知道我需要这样的东西才能访问另一个类上的 TreeSet:
public class MainActivity extends AppCompatActivity {
private TextView tv1,tv2,tv3;
private ArrayList<Obj> ts;
private Gestor gestor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
gestor = new Gestor();
gestor.getGestorTSusers()...
}
private void findViews() {
this.tv1 = findViewById(R.id.tv1);
this.tv2 = findViewById(R.id.tv2);
this.tv3 = findViewById(R.id.tv3);
}
}
上面我正在创建一个新的 Gestor 来访问内部的 TreeSet
,但现在我想访问完全相同 TreeSet
我在这里工作,但在不同的类(class)。如果我只是喜欢
private Gestor gestor;
this.gestor.get....
我使用的是同一个TreeSet
吗?
上下文会有用吗?
做这样的事情最好、最有效的方法是什么?
很抱歉,我知道这看起来很糟糕,但这是我第一次提出这个问题,所以给我一个机会。
最佳答案
如果我正确理解你的问题,你只需要一个 Gestor 实例,并在多个类中使用它。当您将 Gestor 设置为单例时,您将拥有与 Gestor 绑定(bind)的相同 TreeSet<...> 实例。尝试理解单例设计模式的含义,https://www.oodesign.com/singleton-pattern.html .
关于java - 从多个类访问和修改一个类中的ArrayList/TreeSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54579236/