Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to access the elements of a 2 dimensional ArrayList

 
simmi kamal
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have a class say XYZ which contains a method getSFInGroups() and this method returns an ArrayList within an ArrayList in the form of

[GroupName , ArrayList[EventName,SecurityFunctionVO]].

My question is how can I access the individual elements of this Arraylist,
like GroupName, EventName and the various fields inside the SecurityFunctionVO class which is a value object.

Thanks.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Smita,
A 2D ArrayList isn't a built-in concept in Java like a 2D array is. A 2D ArrayList is really just an ArrayList that happens to contain other ArrayLists. As such, keep this in mind when accessing.

This is what you really have in your example:


Consider using a "real" object to store your values. Or a map if you have name/object pairs. Storing different types of objects in an ArrayList is confusing and hard to maintain. Java 5 introduces generics where you can say what type of ArrayList you have. In your case, you don't really have a type. You have a "bag" of objects that you happen to be storing in an ArrayList.
 
simmi kamal
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeanne.
 
Rob Spoor
Sheriff
Pie
Posts: 20751
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jeanne Boyarsky:
A 2D ArrayList isn't a built-in concept in Java like a 2D array is. A 2D ArrayList is really just an ArrayList that happens to contain other ArrayLists. As such, keep this in mind when accessing.

Technically, a 2D array isn't a built-in concept either - it's just an array of arrays.

String[][] is basically (String[])[], so an array or arrays of Strings. Even accessing it, lets say array[1][2] is nothing more than (array[1])[2] - first the value array[1] is retrieved, which is an array which then has its third element accessed. You can do the same thing with arrays retrieved through methods: "string".toCharArray()[2] is perfectly valid, and returns 'r'.

The only real difference is that there is a shortcut for creating. Whereas new ArrayList<ArrayList<String>> only creates the outer ArrayList, new String[x][y] also creates all inner arrays.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic