In Java, is there a way to specify that an argumen

2020-08-13 07:25发布

I am tempted to do such kind of code, using jGraphT

/*
  interface DirectedGraph<V,E> { ...}
  interface WeightedGraph<V,E> { ...}
*/

public class SteinerTreeCalc  {

    public SteinerTreeCalc( < ??? implements DirectedGraph<V,E>, WeightedGraph<V,E> > graph )  {
     ......
    }


}

I want to create a constructor that ask for an object implementing two interfaces.

Update :

In my goal, there are already chosen classes for Vertex and Edges (V and E), but thanks a lot to people who come up with :

public class SteinerTreeCalc <V, E, T extends DirectedGraph<V, E> & WeightedGraph<V, E>>  
{ 
   ....
}

标签: java
5条回答
我命由我不由天
2楼-- · 2020-08-13 08:11

This could be what you want:
Hidden Features of Java

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-08-13 08:13

you can use extends instead of implements in above code

查看更多
够拽才男人
4楼-- · 2020-08-13 08:14

Yes, it's possible:

public class SteinerTreeCalc<T extends DirectedGraph<V,E> & WeightedGraph<V,E>> {
  public SteinerTreeCalc(T graph) {
    ......
  }
}
查看更多
Explosion°爆炸
5楼-- · 2020-08-13 08:19

If V and E are concrete classes rather than type parameters, then you could create a new interface as follows:

public interface DirectedWeightedGraph extends 
    DirectedGraph<V,E>, WeightedGraph<V,E> {
}

then

public class SteinerTreeCalc  {

    public SteinerTreeCalc(DirectedWeightedGraph graph)  {
       ...
    }
}

The problem is that the actual argument must implement the DirectedWeightedGraph interface. A type that just implements DirectedGraph<V,E> and WeightedGraph<V,E> is not sufficient.

查看更多
不美不萌又怎样
6楼-- · 2020-08-13 08:25

Should work like this, but this is complexer generics logic, hope you can adapt:

public static interface DirectedGraph<V, E> {
}

public static interface WeightedGraph<V, E> {
}

public <V, E, T extends DirectedGraph<V, E> & WeightedGraph<V, E>> SteinerTreeCalc(T bothInterfaces) {
    // do it
}

These are the interfaces and the constructor like asked in your question.

查看更多
登录 后发表回答