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

2 Answers2

1

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

Imran
  • 2,514
  • 1
  • 16
  • 19
  • Singleton is absolutely overkill here, and is [not recommended in general for multiple reasons](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons). – Péter Török May 23 '12 at 07:37
  • 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 – Imran May 23 '12 at 08:00
  • 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. – Péter Török May 23 '12 at 08:10
  • hmm, what you code is highly coupled that why i wont go for it. – Imran May 23 '12 at 08:23
  • 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 – Imran May 23 '12 at 08:31
  • Well, good luck then for reducing coupling using a Singleton... ;-> – Péter Török May 23 '12 at 08:34
  • The blog post is fine, although IMHO not very relevant here. Indeed, "things varies App to App and requirements to requirement". That's exactly why one should know a *lot* more about the specific situation before recommending Singleton as a solution. – Péter Török May 23 '12 at 08:39
  • Btw "OP" means "original post" here, in case you decoded it differently. – Péter Török May 23 '12 at 08:41
  • yap i took as "Old Post" :D, Thanks – Imran May 23 '12 at 09:56
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) {
Péter Török
  • 109,525
  • 28
  • 259
  • 326