Andre Roque
Andre Roque

Reputation: 543

Graph representation in Java

I have to make an application that uses Graphs (Data Structure) but I don't know how to represent them, and was asking if you can give me some hints.

Should I create a class Vertex and Edge? If yes, what should be their attributes?

Upvotes: 4

Views: 8799

Answers (4)

Arnout Engelen
Arnout Engelen

Reputation: 6897

This rather depends on your use case, but you might want to try and leverage a 'graph database' like neo4j

Upvotes: 0

mikera
mikera

Reputation: 106351

I suggest using adjacency lists for graphs.

The simplest way is probably to make a Vertex class, which contains an ArrayList<Vertex> list of links to adjacent vertexes. This is sufficient to represent any graph, you don't need a separate Edge class.

You can add whatever other data attributes you like to the vertex class, but the list of links is all you strictly need.

Note that you can have either directed edges (one-way links) or undirected edges (adjacent vertices point back to each other).

Upvotes: 12

ACC
ACC

Reputation: 2560

This is not really specific to Java. The two most common representations are adjacency matrix and list. Details here

If you want a library, JGraphT is nice

Upvotes: 3

Bozho
Bozho

Reputation: 597016

You can represent it the typical ways. See here. For example:

Upvotes: 6

Related Questions