0

I need to create a variable-sized two-dimensional coordinate system. What I've been able to come up with so far is:

Vector<Coordinate> board = new Vector();

for ( int count = 0; count < num_rows; count++ ) {
  board.add(new Vector(num_cols));
}

How do I access the elements within this multi-dimensional vector? I have tried doing board[row][col] but this didn't seem to work.

I'm familiar with using Vectors in C++, but can't seem to figure out how to do this in Java.

Wex
  • 15,539
  • 10
  • 64
  • 107

4 Answers4

2

http://download.oracle.com/javase/6/docs/api/java/util/Vector.html

You need to use .get(index_number) so that becomes board.get(row).get(col)

CPJ
  • 1,635
  • 1
  • 9
  • 9
1

I don't get how you are adding a Vector into a Vector of Coordinates. You might try something like List<List<Coordinate>> board. Then use board.get(1).get(2) to get a position.

What you really might try is the Guava Table. http://docs.guava-libraries.googlecode.com/git-history/release09/javadoc/index.html

Then it would be:

Table<Integer, Integer, Coordinate> board;
board.put(1, 2, new Coordinate());
John B
  • 32,493
  • 6
  • 77
  • 98
  • Great, thank you for both clarifying how to declare the multi-dimensional vectors and showing me how to access the element within that vector. – Wex Sep 06 '11 at 17:48
  • Any specific reason why you suggested using List> instead of Vector>? – Wex Sep 06 '11 at 17:50
  • 1
    Vectors are thread-safe. If you don't need the overhead of thread-safety, don't use it. – John B Sep 06 '11 at 17:58
1

A vector in Java is more like a list than an array. To access the element at position 0 in vector v, use:

v.elementAt(0)

or

v.get(0)

Check the documentation

ben
  • 472
  • 1
  • 3
  • 10
0

I recommend using two-dimensional array:

Coordinate[][] space = new Coordinate[width][height];
...
Coordinate valuableInfo = space[x][y];  
Andrey Atapin
  • 7,745
  • 3
  • 28
  • 34