简体   繁体   中英

Java: Weighted Directed Graph where the vertices are OBJECTS

I need to create a weighted digraph. The implementations I've seen represent the vertices as simple integers, and the edges are represented with adjacency lists. However I need vertices that are represented by objects of a custom class. With this graph I need to perform typical operations (specifically, Dijkstra).

My idea was to hash somehow represent the objects as integers but I wouldn't know how to come up with a hash function that can be converted both ways (ie vertex to int and int to vertex).

If you really want to represent vertices as (unique) integers in the graph, you could use an ArrayList to map from vertices to your objects and a HashMap<MyObject, Integer> to map back. You could wrap this pair in your own class providing getIndex() and getElement() (as sketeched below), which may improve readability.

That said, why not just use http://jgrapht.org or a similar library?

public class IndexMap<T> {
  private List<T> elements = new ArrayList<>();
  private Map<T, Integer> indices = new HashMap<>();

  public int add(T element) {
    int index = elements.size();
    elements.add(element);
    indices.put(element, index);
    return index;
  }

  public int getIndex(T element) {
    Integer index = indices.get(element);
    return index == null ? -1 : index;
  }

  public T getElement(int index) {
    return elements.get(index);
  }

If you don't need to (re)use a pre-existing integer-based graph and can't use a library, you could alternatively implement your own Vertex class than stores an object:

 class Vertex<T> {
   T element;
   List<Vertex<T>> edges = new ArrayList<>();

   Vertex(T element) {
     this.element = element;
   }

   void addEdge(Vertex<t> to) {
     edges.add(to);
   }

   ...
 }

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