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
  • 398,270
  • 210
  • 566
  • 880
Wassim Sboui
  • 1,692
  • 7
  • 30
  • 48

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,187
  • 4
  • 25
  • 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
  • 84,978
  • 11
  • 107
  • 151