Search code examples
javamatrixadjacency-matrix

Adjacency Matrix Implementation


I'm looking for an implementation of a Matrix with keys at first row and first column. First I thought something like a HashMap in a HashMap but this looks ugly and I think it would be wrong. I really need those keys where I can check, if a string exists in the first row as a key. (I want to implement an adjacency matrix)

I'm not sure if I was clear enough. Here a small Picture to visualize it.

Something like this:

Just that the first column and row are not numbers but cities.

In fact I want to save the distances from cities to cities in a adjacency matrix.


Solution

  • Use a custom class as a key in HashMap.

    public class Key {
        private String city1;
        private String city2;
    
        public Key(String city1, String city2){
            this.city1 = city1;
            this.city2 = city2;
        }
    
        //hashCode and equals
    }
    

    then you can use it as so:

    HashMap<Key, Integer> adjacencyMatrix = new HashMap<>();
    adjacencyMatrix.put(new Key("Berlin", "London"), 933);
    
    Integer distance = adjacencyMatrix.get(new Key("Berlin", "Paris"));
    if (distance == null){
        //no entry
    }
    

    Don't forget to generate hashCode and equals in Key class!