How can I specify that a particular parametrized type needs to have a particular method?
What I mean is: If I have my class public class SparseMatrix<type>
, and one of my methods in the class (the add
method) needs to use the add method of its members, how can I make it require that type
has an add
method? I need my SparseMatrix to be able to work with not only numbers and strings, but with other kinds of addable things too, even other matricies.
I would also be using it in my mul
and sub
methods.
You can't just do it based on the presence of a method - the types would have to implement a common interface or superclass. For example:
public interface Addable<T>
{
T add(T lhs, T rhs);
}
Then:
public class SparseMatrix<T extends Addable<T>>
Of course you can't make existing types (numbers, strings) implement that interface - you'd have to write your own applicable wrapper type.
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.