0

I want to implement in Java a matrix with custom index like this example:

         country1 city1 name1 region1 population1
country2    23      5    55    ...
city2       5       9    .
name2                    .
region2                  .
population2

That is mat[country1][country2] should return 23. I don't know how I will do it.

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
Wassim Sboui
  • 1,564
  • 7
  • 29
  • 47

2 Answers2

4

You are likely to have to use Hashmap or HashTable with a key acting like pair to contain the two indexes: Map<Pair<K1,K2>, V>

You can take a look at that for more informations: Map with two-dimensional key in java

Community
  • 1
  • 1
Mesop
  • 5,029
  • 4
  • 23
  • 42
2

If you have two-dimensional tables whose rows and columns always follow this order, then you could use an enumeration of rows/columns.

For example:

   public static final int COUNTRY = 0;
   public static final int CITY  = 1;
   public static final int NAME = 2;
   public static final int REGION = 3;
   public static final int POPULATION = 4;

On the other hand, if you can have multiple countries in the data structure, in both dimensions, then you could use a Map.

Andy Thomas
  • 82,182
  • 10
  • 99
  • 146