Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-dimensional List in Java

Tags:

java

list

Is there a way to handle Lists in Java as twodimensional?

The situation: I have a graph with nodes, edges and weight per edge. Now I need a data structure to store for each node: a) its neighbours b) the edge's weight for each neigbour

First I thought of creating a new class "node" with an identifyer and something like a two-dimensional array to store neighbour-identifyers and edge-weights. But the number of neighbours for each node is not given and may increase dynamically during runtime. Therefore I think two-dimensional arrays are not the way to go here.

I thought it would be possible to have in the class "node" a list like:

List<node> neighbours = new ArrayList<node>();

But obviously this only handles the neighbour nodes - not the weights of their edges.

Does anybody have a hint how to construct such a "graph" where for every node the neighbour's identifyers and the corresponding edge weight are stored?

Thank you for reading :-)

like image 883
coroner Avatar asked Oct 06 '22 10:10

coroner


1 Answers

Most straight-forward is to use HashMap:

    class Edge {
// represents edge with destination node and it's weight
        private final Node node;
        private final int weight;

        Edge(Node node, int weight) {
            this.node = node;
            this.weight = weight;
        }

    }

// represents map which holds all outgoing edges keyed by source nodes.
    Map<Node, Set<Edges>> edgesByOutgoingNodes = new HashMap<Node, Set<Edges>>();
like image 154
Victor Sorokin Avatar answered Oct 10 '22 03:10

Victor Sorokin