• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating an array  RSS feed

 
renu richard
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want the values to be stored in the countries array as below. Below is the javascript code written in JSP. Can anyone please tell me how can i set the values to an array using java by means of for loop. Thanks

var countries=new Array();
countries[0]=new Array();
countries[0]['country']='United Kingdom';
countries[0]['cities']=['London','Manchester','Birmingham','Liverpool','Edinburgh','Cardiff','Belfast'];
countries[1]=new Array();
countries[1]['country']='United States';
countries[1]['cities']=['Washington DC','New York','Los Angeles','Chicago'];
countries[2]=new Array();
countries[2]['country']='Australia';
countries[2]['cities']=['Canberra','Melbourne','Sydney','Brisbane'];
 
Rob Spoor
Sheriff
Posts: 20898
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks like you want an expandable array. Unlike JavaScript arrays, Java arrays have a fixed size. You'll want to use a List instead.

However, a List has only an integer-based index. For other types of indexes you will need a Map instead.

A little example (excluding generics for the moment):


You might want to encapsulate the country + city information into a new class though, just to make it easier:


Instead of a lot of casting and Map accessing, where you can mistype the name (e.g. "Country" instead of "country") you have one single object that has all information.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!