Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best option for two dimensional data - rectangular data - rows columns

 
Bob Smith
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are my options for storing two dimensional data in Java?

I know I could use a two dimensional array, but arrays in java are rather limited since I have to initialize the size. What else can I use to store two dimensional data? What is the best practice?
 
Rahul P Kumar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what are your data, show us sample. If your data is like, you want to get nth row and mth column directly, probably the only option is array. you have sth like all values can be grouped together based on one unique value, you can choose map.
 
Rob Spoor
Sheriff
Pie
Posts: 20526
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A List of Lists is also an option:
However, you need to create all intermediate Lists, something you can do with a shortcut by specifying all sizes in the array initialization.

If you're data structure will be sparse (i.e. contain a lot of gaps) a Map<Point,X> may work as well, as long as you encapsulate it well:
 
Campbell Ritchie
Sheriff
Posts: 48910
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rahul.p Kumar wrote: . . . sth . . .
For reasons explained here, please avoid that sort of abbreviation. People who didn't learn English as a first language won't understand that, least of all after you said "nth" and "mth".

Java doesn't support 2-Dimensional arrays. It supports arrays of arrays, which can be more versatile. For example your array of arrays can include differently sized arrays, or even an empty array, as its elements.
 
Rahul P Kumar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:For reasons explained here, please avoid that sort of abbreviation. People who didn't learn English as a first language won't understand that, least of all after you said "nth" and "mth".


if you want to write mth row, how you will write in this editor, is there any facility to write superscripts?
 
Bob Smith
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the input everyone.

Could I also use a map as follows?

Map<Integer, String[]> mydata = new HashMap<Integer, String[]>();

Integer would represent the row number, and the array of strings would hold the columns?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic