• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to create multidim arraylist and access it

 
Lester D Jones
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could anyone provide an example of how to create a two dimension arraylist and how to get its elements?

thanks

ldj
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Keep in mind that Lists (and arrays) are one-dimensional in Java. You can simulate higher-dimensional constructs by nesting one-dimsenional ones.

So, a two-dimensional array is a one-dimensional array of one-dimensional arrays:


Likewise, a two-dimensional list is a List of Lists:

(note that the use of generics makes the visualization easier)

Access of them is how you would expect. To get the second string of the third array, you first get the third array and then get the second String:


Lists (without Generics) are a little more complicated, but Generics cleans them up:


Hope that this helps.
 
Lester D Jones
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using Jeff's example as a base I want to create a matrix with the parameters of a request object. Here is the snipet:

List<List<String>> matrix = new ArrayList<List<String>>();
while(reqParams.hasMoreElements()) {
List<String> paramNameCol = new ArrayList<String>();
List<String> paramCol = new ArrayList<String>();
paramName = (String)reqParams.nextElement();
paramNameCol.add(paramName);
paramCol.add(request.getParameter(paramName));
matrix.add(paramNameCol);
matrix.add(paramCol);
}
System.out.println(matrix.get(0).get(1));

I would expect to print the parameter but instead the paramenter is in matrix.get(1).get(0). It seems to me that I am adding a row instead of a column. What am I doing wrong?

thanks to all for the help

ldj
 
Campbell Ritchie
Sheriff
Pie
Posts: 48940
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
albert kao,
Your post was moved to a new topic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic