0

I have an array in First.java, den Second.java is suppose to collect data and put inside the array in First.java. den I need Third.java to read from the array to see wad Second.java has entered.

If i use "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?

Thanks in advance

1
  • 1
    Try to write some code, please. Then post your question with code snippet here. Commented May 23, 2012 at 7:23

2 Answers 2

1

Use Singleton Design Pattern, see java sample, for class which holds Array

Sign up to request clarification or add additional context in comments.

9 Comments

Singleton is absolutely overkill here, and is not recommended in general for multiple reasons.
I think Singleton is answer here, reasons 1) he is trying to hold arrays states same as any MODEL(MVC) does, 2) To deal with Static Array he needs to change implementation of other classes, 3) He didnt said he need Array till Application lives, and he need to destroy(set null) to free memmory if he uses static array
The word "static" isn't mentioned anywhere in the OP. The most obvious and safest solution to store data with a limited lifetime is to put it into an object.
hmm, what you code is highly coupled that why i wont go for it.
OP is very useful, but these things varies App to App and requirements to requirement, please see this too jorudolph.wordpress.com/2009/11/22/singleton-considerations – Johannes Rudolph
|
0

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. E.g.

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:

    third.processArrayFromFirst(first.array);

    ...

  public void processArray(Object[] array) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.