Re: Newbie Question - ArrayLists and referencing it
Taria wrote:
Hello all,
Ohhh, thank you so much for addressing those 'unchecked' warnings. I
think I'm up to 15 of them now and have been ignoring them. :)
Thank you guys for excellent advice! I think I spent almost four
hours on that small segment, trying to assign values where I wanted
them to go (instead of them 'magically' appearing somewhere
else. :p) I learned a lot of things by experimenting though.
Arrays and collections don't make a good mix eh? Ok, so I reorganized
my code to exclude the array within an ArrayList. I thought I needed
to do that to create the matrix structure I ultimately wanted. So now
I have an ArrayList of ArrayLists where table's definition not an
array. In short, I've done this (code doesn't include the fix to
remove the unchecked warnings):
....
ArrayList table = new ArrayList();
{ArrayList data = new ArrayList();
data.add(1);
data.add(3);
data.add(2);
table.add(data);
}
{ArrayList data = new ArrayList();
data.add(11);
data.add(13);
data.add(12);
table.add(data);
}
....
This is what worked for me, I assigned a list of data items to each
row of table. And I have a question about those curly braces. I
discovered them last night and it appears they make whatever code in
the middle of them, local within the brackets. I don't remember ever
seeing them used in examples of other ppl's code anywhere before. But
I've found that without them, table assumes the values of only the
last set of assignments instead of 2 unique sets of assignment. Maybe
it's better to make those parts into methods? Just curious about the
usage of those.
Good questions.
The curly braces introduce a "block" of code with "local scope". Within each
block you *redeclared* the variable 'data'. Without the inner sets of curly
braces, the scope of the first declaration would have overlapped the second,
causing a conflict.
However, if you simply *re-use* the variable that problem goes away:
public class Matriculate
{
List< List <Integer> > table
= new ArrayList< ArrayList <Integer> > ();
public Matriculate()
{
// the table will now contain zero rows
assert table.size() == 0;
// here row is declared the one and only time
// and initialized for the first of more than one time
List <Integer> row = new ArrayList <Integer> ();
row.add( 1 );
row.add( 2 );
row.add( 3 );
row.add( 5 );
table.add( row );
// the table will now contain one row
assert table.size() == 1;
row = new ArrayList <Integer> ();
// notice - re-used, not re-declared
// the variable 'row' now points to a whole
// new ArrayList
row.add( 1 );
row.add( 2 );
row.add( 4 );
row.add( 8 );
row.add( 16 );
table.add( row );
// the table will now contain two rows
assert table.size() == 2;
}
// now the variable 'row' is out of scope
// the closing curly brace killed it
public List< List <Integer>> getTable()
{
return Collections.unmodifiableList( table );
}
}
--
Lew