user1411859
user1411859

Reputation:

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

Upvotes: 0

Views: 5690

Answers (2)

Péter Török
Péter Török

Reputation: 116266

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) {

Upvotes: 0

Imran
Imran

Reputation: 3024

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

Upvotes: 1

Related Questions