Problems passing an array to an inner class

M

Matteo

The following piece of code does not work:

final int fNum = num;
final Object[] fItems = items;

SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
betterAddColumn(fNum,fItems);
}
});

It doesn't throws any exception but the contenents of the array are
totally scrambled up inside BetterAddColumn. The int value gives no
problems. Clearly the workaround for "local variable is accessed from
within the inner class; it needs to be declared final" does not work
for arrays.
Is it possible to to pass a vector to a inner class?
I need invokelater because of the swing synchronization event thread
problems modifying a JTable.

Thanks,
Matteo.
 
M

Michael Borgwardt

Matteo said:
The following piece of code does not work:

final int fNum = num;
final Object[] fItems = items;

SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
betterAddColumn(fNum,fItems);
}
});

There's nothing wrong with that code.
It doesn't throws any exception but the contenents of the array are
totally scrambled up inside BetterAddColumn.

Because *other* parts of your code change it.
The int value gives no
problems. Clearly the workaround for "local variable is accessed from
within the inner class; it needs to be declared final" does not work
for arrays.

That's not a workaround. The point is that the inner class gets a *copy*
of the local variables. But in the case of objects (such as arrays)
that's just a copy of the reference to the object. The object itself
is not copied, and if it is changed by other parts of the code before
the inner class runs, the changes will be visible.
Is it possible to to pass a vector to a inner class?

There will be no difference at all.

Either don't change the array after passing it to the inner class, or
make a copy of it and pass that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,176
Latest member
Jerilyn201
Top