Re: Newbie Question - ArrayLists and referencing it
On Nov 11, 5:47 am, Daniel Pitts
<newsgroup.spamfil...@virtualinfinity.net> wrote:
Chris ( Val ) wrote:
public class MyProg1
{
public static void main( String[] args )
{
ArrayList<Integer> data = new ArrayList<Integer>();
ArrayList table[] = new ArrayList[ 5 ];
Arrays.fill( table, new ArrayList<Integer>() );
data.add( 1 );
data.add( 3 );
data.add( 4 );
for( int i = 0; i < data.size(); i++ ) {
table[ i ].add( i, data.get( i ) );
}
}
}
Whoops, Chris, you're wrong :-(
Specifically> Arrays.fill( table, new ArrayList<Integer>() );
This will put the *same* ArrayList into every slot in table.
Wow :-)
My apologies to the OP.
I guess I assumed that "new ArrayList<Integer>()" would
create and add a *new unique copy* of an ArrayList into
each slot of the array.
Seems I have a bit more to learn about Java references.
Thank you for the correction.
While I think the OP is going about this problem the wrong way, the
solution he needed was:
table[i].add(data.get(i));
Yes, I had that originally, but whilst experimenting
with the version I posted, I forgot to revert back to
this one.
To the OP:
Try not to mix arrays and Collections. As a matter of fact, for the
most part its best to deal with Collections, and avoid arrays all together.
Good advice.
--
Chris