Suhail Gupta
Suhail Gupta

Reputation: 23276

How can I make this method return an array?

How can I make the following method return a character array ?

public char[] startThread() {
    // arr declaration
    Runnable r = new Runnable() {
        @Override
        public void run() {
            arr = getArray(); // arr assignment
        }
    };
    new Thread(r).start();
    return arr;
}

char arrNew[] = startThread();

Note : The above snippet generates an error

Upvotes: 0

Views: 124

Answers (2)

gaborsch
gaborsch

Reputation: 15758

You cannot do that.

When you return from your method, you don't have your char array. It is not created yet. So, assigning as a reference will not work. Neither Callable will help on this.

What you can do is that you create a holder object, and return that (this is very similar to Future objects):

public static class ArrayHolder {
    public char[] arr;
}

public ArrayHolder startThread() {

    final ArrayHolder holder = new ArrayHolder();

    Runnable r = new Runnable() {
        @Override
        public void run() {
            holder.arr = getArray(); // arr assignment
        }
    };
    new Thread(r).start();
    return holder;
}

ArrayHolder h = startThread();
char arrNew[] = h.arr;

Notice, that h.arr will change in time, so the first time you call it it will most likely return null

Upvotes: 0

Himanshu Bhardwaj
Himanshu Bhardwaj

Reputation: 4123

Look for java.util.concurrent.Callable, its similar to runnable but returns a value.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html

or

If in 1.6 JDK, you can look for Future objects.

Upvotes: 3

Related Questions