Re: Newbie Question - ArrayLists and referencing it
Taria wrote:
I've tried many different ways to assign a value to the position of my
choice in a data structure, ArrayList and would appreciate any hints
how to do this. My program as follows (short version):
import java.util.*;
public class MyProg1 {
Excellent name for the class. Seriously - many newbies would use a name part
like "Class" for something that we already know is a class. You gave a
correctly-capitalized name that has a meaning - it's your program number one,
hence "MyProg1". Perfect.
public static void main(String[] args) {
ArrayList data = new ArrayList();
Chris ( Val) pointed out:
You are using an "unchecked" ArrayList here, try:
"ArrayList<Integer> data = new ArrayList<Integer>();"
Taria wrote:
ArrayList [] table = new ArrayList[5];
You do not need an array of ArrayList. Your 'table' is not an ArrayList, but
a group of five ArrayLists.
data.add(1);
data.add(3);
data.add(4);
for ( int i = 0; i < 3; i++ ){
//table.add(data.get(i)); //these are 3 different
This failed because data.get(i) is an Integer (not an int), and table needs a
whole ArrayList, not just one Integer.
Also because add() is not a method of an array.
failed ways that I've tried
//table[i]=data.get(i);
This failed because data.get(i) is an Integer (not an int), and table needs a
whole ArrayList, not just one Integer.
You use bracket notation '[]' not parentheses '()' to assign to an array element.
This failed because data.get(i) is an Integer (not an int), and table needs a
whole ArrayList, not just one Integer.
table[0] = data;
}
}
Essentially, I want to assign the first value of data to the first
element of table, the second value of data to table(2,0), and 3rd
element to table(3,0). The statement table[0] = data puts the whole
arrayList data to table(0) which is not what I want.
You cannot do what you want because table is an array of ArrayList, not an
array of Integer.
How do you reference the elements of table? I thought I understood the
referening until now. :x
table[0] = data;
just like you did. Each element of table is a whole entire ArrayList
(possibly empty or null).
Oh, you want table to hold Integers instead of ArrayLists? Then you want:
List <Integer> data = new ArrayList <Integer> ();
data.add(1);
data.add(2);
data.add(3);
Integer [] table = new Integer [5];
for ( int ix = 0; ix < Math.min( data.size(), table.length ); ++ix)
{
table [ix] = data.get( ix );
}
FWIW, arrays and collections make uneasy bedfellows.
--
Lew