Question

In my code i have (E and V are generic types):

E info;
V v1, v1;

If i write:

info = (E) v1 + v2 

I get an error: SparseGraph.java:163: operator + cannot be applied to V,V.

How can i add v1 and v2 to get the result inside the "info" variable? As you can see i'm using this code to create a SparseGraph and info is the information of an Edge of the graph. IF the edge affect vertex "A" and vertex "B", info should be "AB".

Was it helpful?

Solution

You would need to define an Add operation for you to be able to do that. This is because the concept of adding differs as you use different types. For instance, 5 + 9 yields 14 if you treat them as integers, but you get 59 if you treat them as strings (assuming you are using the default implementation of + for string).

So in shorts, your V must implement a method called add (since Java does not support operator overloading, as pointed out here) which takes one or more other V type objects. In this method, you would have the logic you are describing.

public V add(V source)
{
    //logic to add sparse graphs.
}

Also, this line: info = (E) v1 + v2 assumes that V can be casted to E in some way. You might also need to implement a method in V which given a sparse graph, you can get your edges.

As per your question:

Also doing info = (E) v1.toString() + v2.toString() is wrong?

In your case it is. In this case, what you are doing is that you are concatenating the string representations of v1 and v2 respectively. Assuming you did override such methods within your V class so that you can print something you can work with, the + operator for strings does not have the logic you need. Also, you would then need to cast the string into an object of type E, which is most likely to fail.

OTHER TIPS

In Java you can not overload operators. That is you can not directly sum two objects using the + operator. Instead, you need to implement an add(Object) method for instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top