Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

creating an array

 
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
Pie
Posts: 20495
54
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic