将泛型类型加到double中

时间:2018-06-18 22:45:05

标签: java generics

我需要实现一个图表,它将泛型类型元素作为节点,将泛型类型元素作为边缘的标签。当标签是Double类型时,我需要能够计算图形的重量。

public class Graph<V, T> {
  ...

  public Double graphWeight() {
    Double sum = 0;

    for every label T weight {
        sum = sum + weight;
    }

    if(!directed) sum /= 2;

    return sum;
  }
}

这可以以某种方式完成吗?

2 个答案:

答案 0 :(得分:3)

在图表的构造函数中传递和存储DoubleFunction<T>的实例。然后在循环中使用存储的实例:

public class Graph<V, T> {
  ...
  private final DoubleFunction<T> getWeight;
  public Graph(DoubleFunction<T> getWeight) {
    this.getWeight = getWeight;
  }
  public double graphWeight() {
    double sum = 0;
    for every label T weight {
        sum = sum + getWeight.apply(weight);
    }
    if(!directed) {
        sum /= 2;
    }
    return sum;
  }
}

图表的实例是这样创建的:

class Edge {
  ...
  public double weight() {
    ..
  }
}
...
Graph<Vertex,Edge> graph = new Graph<>(Edge::weight);

答案 1 :(得分:1)

以下是我的建议,值得一提。它使用adjacecny矩阵来表示权重,该权重可以是整数或双精度(不确定为什么有人会想要这个),然后是节点的顶点列表。

除此之外还应该使用V和E的接口。

public class Graph <V, E> {
    private List<V> vertices;
    private E[][] adjMatrix;

    public void setVertices(List<V> nodes) {
        vertices = nodes; 
    }

    public void setAdjacecnyMatrix(E[][] adjMatrix) {
        this.adjMatrix = adjMatrix;
    }

    public Object getNode(int index) {
       return vertices.get(index);
    }

    public boolean hasEdge(int srcs, int dest) {
        for (int v = 0; v < vertices.size(); v++) {
            if (adjMatrix[srcs][dest] instanceof Integer && (Integer) adjMatrix[srcs][dest] > 0)
                return true;
            if (adjMatrix[srcs][dest] instanceof Double && (Double) adjMatrix[srcs][dest] > 0)
                return true;
        }
        return false;
    }

    public double graphWeight() {
        double sum = 0;
        int numV = vertices.size();
        for (int s = 0; s < numV; s++) {
            for (int v = 0; v < numV; v++) {
                if (adjMatrix[s][v] instanceof Double) {
                     sum += (Double) adjMatrix[s][v];
                }
                else if (adjMatrix[s][v] instanceof Integer) {
                    sum += (Integer) adjMatrix[s][v];
                }
            }
        }
        return sum;
    }
}

public static void main(String[] args) {
    Graph<String, Double> g = new Graph();
    String[] nodes = {"A", "B", "C"};
    Double[][] adjMatrix = {
        {0., 1., 3.},    
        {1., 0., 2.},     
        {3., 2., 0.}};
    g.setVertices(Arrays.asList(nodes));
    g.setAdjacecnyMatrix(adjMatrix);
    System.out.println("g1: " + g.graphWeight());
    Graph<String, Integer> g2 = new Graph();
    Integer[][] adjMatrix2 = {
        {0, 1, 4},    
        {1, 0, 2},     
        {4, 2, 0}};
    g2.setVertices(Arrays.asList(nodes));
    g2.setAdjacecnyMatrix(adjMatrix2);
    System.out.println("g1: " + g2.graphWeight());
}