[英]How to get Array From Another Class in Java
I have an array in First.java, den Second.java is suppose to collect data and put inside the array in First.java. 我在First.java中有一个数组,Den Second.java应该是要收集数据并放在First.java中的数组中。 den I need Third.java to read from the array to see wad Second.java has entered.
我需要从数组中读取Third.java,以查看是否已进入Second.java。
If i use "First test = new First();" 如果我使用“ First test = new First();” I would get a blank array again...so how do i read from Third.java to see what Second.java has put in First.java's array?
我将再次得到一个空白数组...所以我如何从Third.java读取以查看Second.java在First.java的数组中添加了什么?
Thanks in advance 提前致谢
使用Singleton设计模式 (请参阅java示例 )获取包含Array的类
Either make the array static
(as per @Jigar's suggestion - although this is not recommended due to unit testing and concurrency issues), or preferably pass the proper instance of First
to Third
. 要么使数组成为
static
数组(根据@Jigar的建议-尽管由于单元测试和并发问题而不建议使用此数组),要么最好传递First
到Third
的正确实例。 Eg 例如
class First {
public Object[] array = ...;
}
class Second {
public fillArrayAndPassItToThird(Third third) {
First first = new First();
// fill in the array...
// then pass it to Third
third.processArrayFromFirst(first);
}
}
class Third {
public void processArrayFromFirst(First first) {
// process First.array
}
}
Alternatively, you may prefer passing only the array itself, instead of the full First
object, to reduce dependencies: 或者,您可能希望只传递数组本身,而不传递完整的
First
对象,以减少依赖关系:
third.processArrayFromFirst(first.array);
...
public void processArray(Object[] array) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.