| Author |
Declaring an array without knowing the length
|
Wouter Hermans
Greenhorn
Joined: Oct 16, 2010
Posts: 13
|
|
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.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19230
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Wouter Hermans
Greenhorn
Joined: Oct 16, 2010
Posts: 13
|
|
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
Joined: Oct 27, 2005
Posts: 19230
|
|
Glad to be of help
|
 |
Adam Richards
Ranch Hand
Joined: Nov 03, 2005
Posts: 133
|
|
|
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.
|
 |
 |
|
|
subject: Declaring an array without knowing the length
|
|
|