简体   繁体   中英

Two-dimensional List in Java

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 :-)

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>>();

You could do something like this:

List<Connection> connections = new ArrayList<Connection>();

Where 'Connection' is defined as:

Class Connection {
    private int weight;
    private Node node;

    .... add getters/setters here ....
} 

The Table interface in Guava might be of some use. Ive never used it but Ive heard it's good. This create method may be of some use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM