• Post Reply Bookmark Topic Watch Topic
  • New Topic

Declaring an array without knowing the length  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey all,

Let's say I want to make a grid of x length on each side (like, say, a chessboard), in its own class. I don't know yet how long the grid has to be on each side - that'll depend on user input. I do know that once created the grid will keep its size.

I'd like to know if it's possible to do this as an array of arrays. If the size of the grid is known beforehand it's easy enough (Array[length][length]), but whenever I try to make a constructor that takes the length variable from another class, it complains that I can't use a dynamic reference to something static. Fair enough - but is there a way around this?

The other alternative I know of is to make an ArrayList, but there I run into the problem that I can't seem to wrap my head around creating an ArrayList of ArrayLists through a for-loop.
 
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wouter Hermans wrote:I'd like to know if it's possible to do this as an array of arrays. If the size of the grid is known beforehand it's easy enough (Array[length][length]), but whenever I try to make a constructor that takes the length variable from another class, it complains that I can't use a dynamic reference to something static. Fair enough - but is there a way around this?

Can you show us how you are trying to create your array? Because what you want should be possible.
 
Wouter Hermans
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you show us how you are trying to create your array?




Looks silly in retrospect, doesn't it?

Your code works like a charm - for some reason I had the idea in my head that I needed to declare the size of the board in the variables up top.
 
Rob Spoor
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Glad to be of help
 
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just a general comment: I assume you know that you can't change the array size once it's declared. If the array size never needs to change, that's fine. But if the size is unknown at compile time, you're better off using a collection class like ArrayList; objects of this class can dynamically grow or shrink as needed at run time.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!