How do I build an array of objects with a Java 5 for loop?

How do I build an array of objects with a Java 5 for loop?

I'd like to populate an array simliar to:

private static final SelectItem[] stateItems = new SelectItem[] {
        new SelectItem("Nebraska"),
        new SelectItem("Texas"),
        new SelectItem("Kansas"),
        new SelectItem("Iowa"),
};

in a loop.

Each SelectItem object value comes from a data source that I can loop through with a Java 5 for statement.

However, what is the proper approach to populate the SelectItem[] stateItems array?

I guess, I get used to using ArrayList, which has an add() method.

Any suggestions or examples are appreciated.

Thank you,

--Todd

jtp51Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Mayank SConnect With a Mentor Associate Director - Product EngineeringCommented:
If you have them in an array-list/ collection, you can also directly use the toArray () method to get the values in an array.
0
 
Ajay-SinghCommented:
List<SelectItem> list = Arrays.asList(stateItems);
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
mukundha_expertCommented:
>> How do I build an array of objects with a Java 5 for loop?

Object[] obj = new Object[5];
for ( int i =  0 ; i <  array.length ; i ++  )
 obj[i] = new Object() ;



>>SelectItem object value comes from a data source that I can loop through with a Java 5 for statement

if you can get the data from the statement, then form a array of that value ( String array)

say, String[] data = { your values} ;

for ( int i = 0 ; i < stateitems.length ; i ++ )
   stateitems [ i]  = new SelectItem ( data[i] ) ;


if you are using arrayList then,

ArrayList stateitems = new ArrayList () ;
for ( int i = 0 ; i < data.length ; i ++  )

stateitems.add ( new SelectItem ( data [ i ] ) ) ;

0
 
mukundha_expertCommented:
>>private static final SelectItem[]

if the array is final then you cannot change its reference later, it should be initialzed once it is declared,
0
 
ksivananthCommented:
SelectItem[] stateItems = new SelectedItem[ 5 ] ;

for( int i = 0; i < 5; i++ ) stateItems[i] = new SelectedItem() ;

Not sure if this is what u wnated ;)
0
 
Mayank SAssociate Director - Product EngineeringCommented:
They are not Java 5 for loops. But anyway, why would you want to use the enhanced for loop? I personally don't prefer it as it doesn't give as good performance as the simple for loop.
0
 
CEHJCommented:
Using new for loop would be something like

int ix = 0;
for (SelectItem si : dataSource) {
    stateItems[ix++] = si;
}
0
All Courses

From novice to tech pro — start learning today.